Bash is a commonly used shell on the Linux OS, and learning to write scripts in Bash is a great way to automate common server-side tasks using a Crontab entry or by submitting requests to a bash script through a web interface, for instance. No one wants to constantly do something manually if they could figure out a way to automate the process, so today we’ll discuss some beginner’s syntax to get you started on your way to automating the planet.

To create a script which can be run later via the command line without having to specify the entire path to the script, the script must reside in a directory which exists in your $PATH. On most Linux distributions you can place the script in /usr/local/bin/ if you want all users to access the command or /usr/local/sbin/ if you only want the superuser (root) to access the command.

The first line of your bash script should contain what is known as a she-bang:

In UNIX-speak, the # symbol is known as a “hash” and the ! is known as a “bang” so together they were known as a hash-bang or shebang for short. This line tells the operating system to invoke the specified shell to execute the commands that follow in the script.

Often, you may want to set some static variables at the top of your script, so you can offer a way for users to customize a path to a binary or directory, or other configuration values. To set a variable, add the following:

Now you can use $WEBROOT in your code and it will print out the specified value for use in dynamic commands later in the script:

You can also set a variable to contain the output that results from running a command:

Bash scripts can also accept values input from the command line, seperated by a space. For instance, if the user ran the command:

Then the $1 variable would contain the string “value1”, the $2 variable would contain the string “value2” and so on.

Conditional statements in bash are as follows:

Or you can include an else condition:

Or you can include an else if condition:

Unary expressions can be used to examine the existence of a file or directory, or to test the length of a string. The following is an example of testing for the existence of a file:

The following is another example, this time testing for the existence of a directory:

The Introduction to if section of the Bash Guide for Beginners is a great place to get more information.