Writing scripts
There are series of commands that you need to run regularly. Instead of having to type them each time, you can write them in a text file (called a script) with a .sh
extension and execute that file whenever you want to run that set of commands. This is a great way to automate work.
This section covers scripts syntax and execution.
Writing and executing scripts
Scripts as arguments to bash
A shell script is simply a text file. You can create it with a text editor such as nano which is installed on most systems.
Let’s try to create one that we will call test.sh
:
nano test.sh
In the file, write the command: echo This is my first script
.
This is the content of our test.sh
file:
test.sh
echo This is my first script
Now, how do we run this?
We simply pass it as an argument to the bash
command:
bash test.sh
This is my first script
And it worked!
Shebang
There is another way to write and execute scripts: we can use a shebang.
A shebang consists of the characters #!
followed by the path of an executable. Here, the executable we want is bash
and its path is /bin/bash
.
So our script becomes:
test.sh
#!/bin/bash
echo This is my first script.
Now, the cool thing about this is that we don’t need to pass the script as an argument of the bash
command anymore since the information that this should be executed by Bash is already written in the shebang. Instead, we can execute it with ./test.sh
.
But there is a little twist:
./test.sh
bash: ./test.sh: Permission denied
We first need to make the file executable by changing its permissions.
Unix permissions
Unix systems such as Linux use POSIX permissions.
To add an executable permission to a file, you need to run:
chmod u+x test.sh
Now that our script is executable, we can run:
./test.sh
This is my first script
Here and here are two videos of a previous version of this workshop.
Comments
Anything to the right of the symbol
#
is ignored by the interpreter and is for human consumption only.Comments are used to document scripts. DO USE THEM: future you will thank you.