Writing scripts

Authors

Alex Razoumov

Marie-Hélène Burle

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.

Using other computing languages in Bash

It is possible to incorporate scripts written in other computing languages into your bash code.

Example:

function test() {
    randomFile=${RANDOM}${RANDOM}.py
    cat << EOF > $randomFile
#!/usr/bin/python3
print("do something in Python")
EOF
    chmod u+x $randomFile
    ./$randomFile
    /bin/rm $randomFile
}

EOF is a random delimiter string and << tells Bash to wait for that delimiter to end the input.

Here is an example of this syntax:

cat << the_end
This text
will be printed
in the terminal.
the_end