Posted on Wednesday, June 18th, 2014 at 10:21 pm
This tutorial will discuss some beginner's syntax for Bash scripting.
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:
cp -Rv ./data $WEBROOT
You can also set a variable to contain the output that results from running a command:
TODAY=`date +%Y_%m_%-e` echo 'today is '$TODAY
Bash scripts can also accept values input from the command line, seperated by a space. For instance, if the user ran the command:
$ myscript value1 value2
$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:
if [ "$1" != '' ]; then cp -Rv ./$1 $WEBROOT fi
Or you can include an else condition:
if [ "$1" != '' ]; then cp -Rv ./$1 $WEBROOT else echo "You must specify a directory to copy" fi
Or you can include an else if condition:
if [ "$1" != '' ]; then cp -Rv ./$1 $WEBROOT elif [ "$1" == '' || "$1" == 'help' ]; then echo "Please specify a directory to copy" fi
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:
if [ -f "$WEBROOT$1.sql" ]; then rm -v $WEBROOT$1.sql fi
The following is another example, this time testing for the existence of a directory:
if [ -d "$WEBROOT" ]; then mkdir $WEBROOT$1 fi