What is a Bash Script?
In computer programming, a script is a program or sequence of instructions that is interpreted or carried out by another program rather than by the computer processor (as a compiled program is). — searchenterpriselinux.techtarget.com
So basically, a bash script is a file in Linux that can be used to automate a list of commands that you normally execute in a specific order. In a bash script, bash is the scripting language we are using. Bash is short for Bourne Again Shell and comes pre-installed on most Linux machines. A bash script can be written in any text editor, and usually saved with a file extension of
.sh, however the
.sh file extension is optional.
We can use a Bash script to simplify repetitive tasks. For example, to change the WiFi card’s MAC address using the “macchanger” utility (built into Kali Linux) we run the following commands:
ifconfig wlan0 down macchanger --mac 00:11:22:33:44:55 wlan0 ifconfig wlan0 up dhclient wlan0
Info: The above code is assuming that you are trying to change the MAC address of your wlan0 device, which in my case is my wireless network adapter. You can check your connections using
iwconfig in Terminal.
Now, it’s okay if you want to keep typing the above commands every time you want to change your mac address, however it can get annoying after a while. Wouldn’t it be easier if we could just run a simple script that could automatically run the commands shown above? The answer is, Yes. In the following article, I am going to teach you how to create a very basic Linux Bash script, without creating the infamous “hello world” script. 🙂
Creating your first Linux Bash Script
Personally I am tired of “hello world” programs. They are only interesting when you learn your FIRST programming language. After that, you get sick and tired of the basic “hello world” program simply because it doesn’t do much. That being said, Bash scripts are a good way to learn some basic programming techniques if you are new to the programming world.
Anyhow, I decided that we will create a script that will hide our MAC address using macchanger. It’s just a couple more lines of code when compared to the basic “hello world” Bash script and is somewhat more useful.
Our bash script will allow us to simply type
hidemac in our Terminal window, and it will execute the commands shown above automatically. Can you see how this can help administrators and users save time?
To illustrate, open your favorite text editor and paste the following:
#!/bin/bash #Start Linux Bash Script Example echo "changing wlan0 mac address. putting wlan0 down" ifconfig wlan0 down echo "assinging fake mac:" macchanger --mac 00:11:22:33:44:55 wlan0 echo "mac changed. putting wlan0 up" ifconfig wlan0 up echo "ifconfig output:" ifconfig wlan0 dhclient wlan0 #End Linux Bash Script Example
You can also use “macchanger -r wlan0” instead of specifying a mac. This will randomize the mac address. For more information about macchanger, click here.
Bash Script Explanation
- The first line,
#!/bin/bashis important for every Bash script. The
#!portion tells the system that this is a script, and the
/bin/bashportion is the path to the Bash interpreter that will be utilized by the system. This is also one of the reasons you do not have to give your Bash files a
echoprints a string on the terminal screen to let the user know what the script is currently doing.
#allows you to leave a comment in your Bash script.
- The rest of the code are just commands that we would normally type in the terminal one after the other, only in this case, the script will take care of it for us.
Now, save the Linux bash script example file (anywhere for now) as
hidemac (notice we are not using the .sh extension). We have to figure out where to put (install) our hidemac bash script. If you created the
hidemac in the /Documents/Scripts/Bash/ directory, you will only be able to run it by pointing your Terminal to that directory first (see below), or call it by typing the entire directory structure in your Terminal window. Installing the hidemac file will let us run it from any directory in the Terminal.
To run the script from your current directory, type the
./ in front of the script name as shown below:
Install Linux bash script
Linux generally has a list of locations (directories) where it will look for Bash shell script or executable (program) files, if not found it will output
command not found. To figure out where your copy of Linux looks for your bash script files, type the following in terminal:
root@kali:~# echo $PATH
You should get the locations output in the following format:
This means, I can put the
hidemac Shell script file in any of the locations specified above (separated by “:”) to install it (or, be able to run it from any directory in Terminal). I will put my
hidemac file in
/bin folder, but you can put it in any of the locations given to you by your
$PATH command. So the final location for our Shell script is
Bash Script File Permissions
After moving the file, we need to give it permissions to execute. Bash scripts are executed much like applications, and much like applications, they need to have the proper permissions set in order to execute. This is done by running
chmod command in the Terminal. So open up Terminal and type:
root@kali:~# chmod +x /bin/hidemac
Bash Script Execution
Finally, you should be able to open up Terminal and execute the script we just created.
If successful, your bash script should execute and print the
iwconfig wlan0 output to your Linux Terminal screen. The output should have the new device MAC address listed:
New MAC address highlighted in purple
That’s it! Congratulations, you have officially created a working script that you can actually utilize. Beats making a “hello world” script, huh? As you can see, scripting can be very useful when automating repetitive tasks.
Another (quicker) way to make same bash script
First, type the following commands in terminal:
root@kali:~# cat > /bin/hidemac
Afterwards, copy and paste the code for our hidemac bash script (above). CTRL+V may not work, you may have to right-click terminal and select “paste” from menu. Press CTRL+D when you are done pasting the text. This will exit the editor and save the file. Now, all you have to do is set the permissions, so type:
root@kali:~# chmod +x /bin/hidemac
Finally, you’re done. As a result, you can open terminal and run the
hidemac bash script.
Bash Script Basics – Image resize example
hidemac provides a good example of what Bash can be used for, it only covers the basics. Just like other scripting languages, Bash is capable of handling user input, variables, conditions and loops. Here is an example of a script I wrote to resize a image using ImageMagick’s Convert command:
Important: ImageMagick must be installed for the below script to work.
#!/bin/bash #TechSide Image resize by percentage #define result variable result="unknown" #format date/time for our log file now=`date +%Y-%m-%d:%H:%M:%S` #ask user for image name & save user input into variable imgName echo "Please enter the image name with extension: " read imgName #ask what percent to resize image & #save user input into variable percento echo "Your Image name is $imgName. By what Percent do you wish to resize $imgName?" read percento #if percent is greater than 0 then convert and name the new image if [ $percento -gt 0 ]; then convert "$imgName" -resize "$percento"% "$imgName"-"$percento".png echo "Thumbnail created. log.txt file updated." result="success" #otherwise provide user update else echo "invalid percent value. Image not resized." result="failed" fi #create/append to log.txt file cat <<EOF >> log.txt $now - Thumbnail $imgName-$percento.png creation result: "$result". EOF
There’s still a lot that can be done with the above code such as better error handling, better thumbnail naming convention, or provide a way to resize based on pixels instead of percentages, etc., but I just wanted to demonstrate some other Bash techniques quickly.
Image Resize Bash Script – Further Explanation
I commented the above code as best as possible, however, if you need further explanation, reading this may help.
First, we declared 2 variables (
now) which will come in useful for a log file. Remember, in Bash, you declare a variable using the = sign, and call it with the $ sign. We then ask the user to type in the full name of the image file using
echo to print to the screen, which will be stored in the imgName variable. Notice how in the 2nd echo command, the variable imgName is called with the $ sign in front (
$imgName). We then ask the user by what percent he/she wishes to resize the image and save it to the
percento variable using
read allows us to save the user input to a variable.
After we have gathered the necessary data, we use an if/then/else condition to verify that the user entered a percent value that is greater than 0
if [ $percento -gt 0 ]; then.
-gt stands for greater than,
-lt: less than,
-eq: equals, and finally
-ne stands for not equal to, however these will only work if comparing numbers, not strings. The script then goes on to
convert (ImageMagick command) the image to the percentage provided by the user, names the generated thumbnail, and updates
result variable to “success”.
Else, (if the user enters 0) the script will notify the user of an invalid argument and update the
result variable to “failed”.
fi ends the if/then/else condition.
Finally, the script generates a log file that outputs the date/time (
$now variable), new image name (
$imgName-$percento.png) and whether the operation failed or succeeded (
$result variable) to a log.txt file in the same directory as the script.
cat <<EOF >>...EOF appends the log entry to a log.txt file every time the script is run. If the log.txt file does not exist, it will automatically create a new file.
As you can see, Bash is powerful and useful skill to have. It can help you quickly create scripts to take care of repetitive tasks. Whether resizing images, or renaming files at the office, I’m sure everyone can find a way to incorporate a Bash script file into their lives. It is fairly easy to learn, has been around since 1989, and will most likely still be around for a while.
Although our Linux Bash scripts were on the smaller side, they are only an examples. Feel free to modify them to suit your needs. For more on Linux Bash script files, please see:
HowToGeek: The beginners guide to shell scripting