Bourne-Again SHell (BASH) is a Unix shell available by default on Linux. This short article will explain how to write bash scripts and provide some examples.
The first line in a bash script should always be: #!/bin/bash. The # is not a comment in this case. #! Is called “shebang” and is used by the shell to decide which interpreter to run the rest of the script, in this case /bin/bash.
After the first line, starting a line with # means everything on that line is a comment.
Now let’s create our first script:
sudo vi /home/firstScript.sh
And place this amazing content to show the date 🙂
#!/bin/bash
date
To be able to run the script, we need to give it execute privileges:
sudo chmod +x /home/firstScript.sh
And now let’s run it (and find out what date is today):
/home/firstScript.sh
Let’s edit our script and make it a little nicer:
sudo vi /home/firstScript.sh
And replace the contents with the following:
#!/bin/bash
echo Today’s date is:
# This is a comment - the following command adds a format to the date
date +"%m-%d-%y"
Now let’s create another script which includes reading input from the user, an if statement, a for loop and use of some variables:
sudo vi /home/secondScript.sh
And paste this content:
#!/bin/bash
echo Name:
read myName
echo Hello $myName
# Let's add some punctuation to it :), Notice the -e to paramer to add line break for \n
echo -e '\nWith punctuation\nHello,' $myName! '\n'
colors=("Red" "Blue" "Green")
for i in {0..2}
do
echo Color $i is ${colors[$i]}
done
echo -e '\nEnter a number'
read myNumber
if [ $myNumber -lt 5 ]
then
echo Number is less than 5
else
# if you do not enter a number, an error will occur but the script will not stop
echo Number is greater or equal to 5, or you did not enter a number
fi
Don’t forget the permissions 🙂
sudo chmod +x /home/secondScript.sh
And run it:
/home/secondScript.sh
You created and ran some bash scripts. Perfect.
Now it’s to time to write scripts that actually do something useful (e.g. backup you database, files, etc.)