Scripts and functions

Shell scripts (9 min + 3 min)

We now know a lot of UNIX commands! Wouldn’t it be great if we could save certain commands so that we could run them later or not have to type them out again? As it turns out, this is extremely easy to do. Saving a list of commands to a file is called a “shell script”. These shell scripts can be run whenever we want, and are a great way to automate our work.

Here is a an example of processing files with scripts:

Variables (7 min)

Functions (13 min)

Functions are similar to scripts, but there are some differences. A bash script is an executable file sitting at a given path. A bash function is defined in your environment. Therefore, when running a script, you need to prepend its path to its name, whereas a function – once defined in your environment – can be called by its name without a need for a path. Both scripts and functions can take command-line arguments.

A convenient place to put all your function definitions is ~/.bashrc file which is run every time you start a new shell (local or remote).

Scripts in other languages

As a side note, it possible to incorporate scripts in other languages into your bash code, e.g. consider this:

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
}

Here EOF is a random delimiter string, and << tells bash to wait for the delimiter to end input. For example, try the following:

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