1. Create and run a script
-
Let's create a script that prints "Hello World!".
vim hello.shPress
ithen type this code:echo "Hello World!"
echo "This is the first script."Press ESC then type
:wqto save and quit.ls -l hello.shcat hello.shcat hello.sh | bashbash hello.shWe are sending it to
bash, and bash is interpreting and executing the commands inside the script. -
We can tell the shell to use Bash for interpreting this script by adding
#!/bin/bashas the first line of the script.vim hello.shPress
1G,O, and then type#!/bin/bash.Press ESC,
:wqand Enter, to save and quit.cat hello.shThe script now should look like this:
#!/bin/bash
echo "Hello World!"
echo "This is the first script."The shebang
If it was a Python script, we would have used instead the line
#!/usr/bin/python3to tell the shell that it should use Python for interpreting this script.The character
#is usually called hash, and!is usually called bang. Together they are called shebang and they are placed at the very beginning of a script (no empty lines and no empty spaces before them). After the shebang comes the program that the shell should use to interpret the script. -
Let's try to execute it:
hello.shIt says
command not found. This is because the shell looks for this command in certain directories, which are listed on the environment variablePATH:echo $PATHThere is no command
hello.shin any of these directories, so shell cannot find such a command.To fix this problem, we can tell bash the path of the command, like this:
./hello.shWhen we give a path to the command (
./in this case), the shell does not use the variablePATHbut tries to find the command in the given path.Modifying
PATHAnother way for fixing the problem is to add the current directory to the
PATH, like this:echo $PATH
PATH="$(pwd):$PATH"
echo $PATHThen the shell will be able to find
hello.sheven if we don't specify its path:hello.sh -
Now, when we try to execute the script, it gives the error message
Permission denied, because the script is not executable. Let's fix this by giving it thexpermission, and try again:ls -l hello.sh
chmod +x hello.sh
ls -l hello.sh
./hello.sh -
In bash, comments are denoted by a
#. Everything after a#is considered a comment and is ignored:ls -l hello.sh # this is a comment and will be ignored
# This is also a comment.Let's modify the script by adding some comments, and execute it again, to verify that the comments are just ignored by the interpreter.
vim hello.shType
1G,oand then enter# This is a comment.on the second line.Press ESC,
j,Aand append# this is another commenton the third line.Press ESC, then
:wqand Enter, to save and quit.cat hello.shThe script now should look like this:
#!/bin/bash
# This is a comment.
echo "Hello World!" # this is another comment
echo "This is the first script."Let's execute it and make sure that the comments are just ignored:
./hello.sh