1.3 Setting Up Shell Scripts

Authored by Atri

Sometimes you may want to run a series of commands without needing to manually enter and execute them yourself. Bash allows you to run shell scripts (text files with a .sh extension), which contain predefined commands, functions, and more. These can be useful for orchestrating a pre-defined workflow, or many other things.

Making a Shell Script

Shell scripts are defined as an executable text file with a file name ending in .sh. Typically speaking, all shell scripts are written with a comment (often called a “shebang”) at the top, followed by all relevant commands and script functions after.

#!/bin/bash

# Normal commands below
echo "Hello world!"

Understanding the Shebang

The shebang is a line present in a shell script which determines the shell environment to run the commands under. This can be beneficial to include to ensure your scripts run in a supported shell environment (such as in circumstances where a system has bash and other shells installed).

The shebang is most commonly set as #!/bin/bash, but it can be pointed to any shell which is installed.

Bash execution flags

Bash supports a number of execution flags which determine how commands are processed by the shell. These can be useful for debugging, or could be used for other purposes. Here are some of the common ones you can look out for:

Flag Description
-a Treat variables and functions defined in a script as exported to the environment of subsequent commands
-e Immediately exit if a pipeline returns a non-zero status
-f Disable filename expansion
-u Treat unset variables as an error when performing expansion
-v Print script lines to standard error as they are read
-x Print commands to standard error after expansion and before execution
Warning

It is wise to use the -v flag over -x in most cases, as -x is able to leak secrets when expanding parameters before we print commands to standard error. The -v flag functions similarly to -x, but simply prints each script line as it gets executed, without processing any parameters.

Running A Shell Script

To run a shell script, you will need to first ensure your shell script is marked as executable. You can do this by running chmod +x your_script.sh on your script file. This will ensure that its read as executable by the host machine.

From there, you may execute a shell script by simply calling it like so: ./your_script.sh