How to Write Your Own Bash Scripts to Automate Tasks on Linux « Null Byte :: WonderHowTo

Bash scripting is a convenient way to automate things on any Linux system, and we're going to use it here to automate certain tasks we use all the time.Bash is a simple language for stringing together several different Linux utilities. Its simplicity makes it easy for beginners to create lots of scripts that would otherwise be pretty complicated or require some pretty hefty programming skills.If you know the right Bash commands, you can do all sorts of things. In this guide, we'll use Bash to automate a few commonly used tasks. We'll also cover aliasing briefly, which will make things even more convenient. For instance, if we have something we want to do, we'll just use an alias command to call a Bash script and have it run whatever it's programmed to do so that we don't have to run and call the script manually every time from wherever it's saved.RequirementsTo follow along, all you'll need is anUbuntuorKali Linuxsystem. Really, any Linux system will do. If you want to pick up a Linux system and you've never tried this before, you can always grab aRaspberry Pioranother single-board computerto run a Linux build on.On Amazon:Great Deals on Raspberry Pi BundlesStep 1: Find You Bash InterpreterTo get started, we need to know which Bash interpreter we're using. To do so, usewhich bashin a terminal window. Learning the location of the interpreter will be useful when writing our first Bash script.~# which bash

usr/bin/bashStep 2: Make Your First Bash ScriptTo start a new Bash script, create and open a new Bash file called "bash.sh" or whatever you want to call it. The important thing is that it ends in the "sh" extension. We'll be creating a super basic script to illustrate one easy thing it can.~# nano bash.shIn the document, start the first line with a shebang (#!) followed by the location of your Bash interpreter (for me, it'susr/bin/bash). When the program is opened, this will tell it how to interpret the language we're writing the rest of the script in.#! /usr/bin/bashLet's create a variable to make something happen. For something simple, we'll just use aSTRINGthat saysNull Byte. You could make it say whatever you want.STRING="Null Byte"Now we want toechosomething back. In our example, we'll echo"Hackers love to learn on $STRING"where $ indicates a call to a variable, in this case, STRING. What this will do is print the message, swapping out $STRING for whatever your STRING is.echo "Hackers love to learn on $STRING"Here's what the script should look like as a whole:#! /usr/bin/bash
STRING="Null Byte"
echo "Hackers love to learn on $STRING"Save your script by hittingControl-Xon your keyboard to exit, thenYto save the modified buffer, and thenEnterto save the file. This will bring you back to the terminal window. To test out the script, usebash bash.sh(or whatever you named it) to call the script. You should see the echoed message appear. Success!~# bash bash.sh

Hackers love to learn on Null ByteStep 3: Use Positional VariablesLet's go back into the Bash script and try out some positional variables, so nano back into the bash.sh file. This time, instead of having a STRING already in the program, we want the user to pass variables into the script. Since we want to try out multiple variables, we'll need to indicate their order.In our example, we'll change the script to a fill-in-the-blank program that saysecho "I firmly believe that $1 is the best $2 for the office of $3"(you could make it say anything you want). The dollar signs are calling variables, and the numbers say in what order. That way, when someone tries to run the script, they can add variables to the end ofbash bash.shbefore running it. We're putting in a simple 1, 2, 3 order, but you could change it to 3, 2, 1 or 2, 3, 1 if you wanted.#! /usr/bin/bash
echo "I firmly believe that $1 is the best $2 for the office of $3"Save your script again withControl-X, thenY, thenEnter, and you'll be back at the terminal window. To test out the script, usebash bash.sh(or whatever you named it) to call the script, but this time, let's add some variables with each one within its own double quotation marks. If you're only using single words for each variable, you don't need the quotation marks.~# bash bash.sh "Vermin Supreme" "candidate" "president"

I firmly believe that Vermin Supreme is the best candidate for the office of presidentEach variable should have taken over the $1, $2, and $3 positions in the printed text. The first given variable would take the $1 slot, the second would take over $2, and the third would go where $3 is. In our example, that gives us "I firmly believe that Vermin Supreme is the best candidate for the office of president."As you can see, Bash scripting is a straightforward way to take in a couple of things like variables and distribute them throughout your script. That way, you can adapt to something that might be piped in from another script or otherwise selected by the user.Step 4: Run Commands & Return Their OutputNext, we want to try to create something inside the script that depends on another tool being run. So nano back into the script and replace the echoed text with something that results from something being run.In our example, let's print the result of a particular command. Afterecho, use a$right away, but this time add parentheses right after it. Whatever command we put inside the parentheses will be run when the program is activated, and the result of the command will be what's printed to the user.You could use something likeifconfig, but to make it easy, we're going withwhoami, which will tell the person running the script what user on the system they are currently using.#! /usr/bin/bash
echo $(whoami)Save your script again withControl-X, thenY, thenEnter, then test out the script withbash bash.sh(or use whatever you called it). As you can see, I'm currently the "root" user, which isn't surprising seeing that my prompts in the terminal end with a # sign.~# bash bash.sh

rootStep 5: Take User InputSo what about interactivity? Bash scripting has that down as well. Open thebash.shfile back up in nano, and we'll create a script that asks the terminal user to input something, which will then be our variable for whatever we want to print out with echo.For our example, we'll useechoto print to the user"What is your name?"Then, on the next line, we'll add a variable ofnamewith thereadcommand. Whatever they input after being asked the question will be seen by our program. To use the variable, let's useechoto print a statement about the name they inputted. The statement uses$nameto indicate it should be swapped with the variable they give us.#! /usr/bin/bash
echo "What is your name?"
read name
echo "Wow, $name sounds like a punk"Save your script again withControl-X, thenY, thenEnter, then test out the script withbash bash.sh(or use whatever you called it). As soon as it's run, it'll ask the user for their name. What we've done here was added a bit of interactivity. They'll type out their name and hitEnter, and instantly, our program will see the name, use that instead of "$name" in the echo command, and print the statement out for the user.~# bash bash.sh

What is your name?
Retia

Wow, Retia sounds like a punkWe've just created an argumentative Bash script that can take in something and insult the user. However, this is far more useful in other scenarios. For example, putting in a variable to see where a particular interface is, which port an Arduino board is connected to, or to flash a bunch of microcontrollers simultaneously. The first step to that last one is selecting which port they're connected to, so custom Bash tools can be pretty convenient.Step 6: Create If StatementsLet's try something a little more advanced, which areifstatements. We can use conditional statements to put controls in our program to see whether something exists or matches a specific value. Let's go back into thebash.shscript and change a few things.If we want to see whether or not the user has actually input a name, we can use anifstatement. This is a pretty typical example. So let's keep the firstecholine where it is, as well as thereadline. But let's swap out the secondechocommand with differentecholines forifandelse.Useiffollowed by a space, then add a pair of brackets. Inside those brackets, put the variablenamewith spaces on each side of it. If you skip the spaces, you'll get an error. Afterward, type a semicolon (;), another space, andthenfor the ending. On the next line, indent and put anechostatement. Here, we'll just use"$name sounds alright to me"to keep it simple. So if someone inputs a name to the program, it will recognize it and print that statement out with their name instead of "$name."But what if somebody just hitsEnterto skip the question? On the next line, putelsein, and that's it. On the following line, indent and add anotherechoprintout. We'll go with"Doesn't sound like anything to me"to tell them they have no name.Lastly, on the script's very last line, add theficommand, which just says that the script is finished. Without this, you'll get errors because when you have loops such as anifstatement, they don't end automatically — you have to tell them to quit.#! /usr/bin/bash
echo "What is your name?"
read name
if [ $name ]; then
    echo "$name sounds alright to me"
else
    echo "Doesn't sound like anything to me"
fiIf the user wants to input a first and last name, we need to make one tiny change to this script. If not, you'll get a "null: unary operator expected" error, and it will result in the else echo being printed. What you need to do is put double quotation marks around $name in the if line. Doing that should allow more than one word for the name input.#! /usr/bin/bash
echo "What is your name?"
read name
if [ "$name" ]; then
    echo "$name sounds alright to me"
else
    echo "Doesn't sound like anything to me"
fiSave your script again withControl-X, thenY, thenEnter, then test out the script withbash bash.sh(or use whatever you called it). Run the script, and you'll get the prompt to enter your name. If you enter your name, it'll say that it "sounds alright."~# bash bash.sh

What is your name?
Retia

Retia sounds alright to meHowever, if you just hitEnterwithout typing any characters, it will use the else to say that it "doesn't sound like anything." So the script is reacting to you.~# bash bash.sh

What is your name?

Doesn't sound like anything to meHaving a program that can react to user input is important if you want to start using Bash scripting to do more advanced things.Step 7: Use Bash in Terminal CommandsI'm not going to do anything else with the script we've been messing with. Instead, we'll try out some terminal commands relevant to Bash scripting and are super easy.Let's say that we want to learn something about the computer, and we don't want to pipe through a whole bunch of different outputs. Without a Bash script, you could type something likeifconfigto get a whole lot of information about the computer's interface parameters. To narrow it down, you could pipe it intogrepand target more specific information. Soifconfig | grep broadcastis a good example.~# ifconfig | grep broadcast

inet 192.168.1.169 netmask 0xffffff00 broadcast 192.168.1.255Above, you can see that I've identified my IP address, which is in a string that has the word "broadcast" in it. So if you wanted to find your current IP address on the network with a one-liner, you could use this not to have to dig into a ton of information just to find one piece of data.Let's try that again, but let's narrow it down to just the IP address. For that, we can use a tiny Bash script. Keep everything the same, but add another pipe to the end, followed byawk '{print $2}'— awk lets us choose a specific word from the output, and print $2 will pull the second item in the output and print it back to us.~# ifconfig | grep broadcast | awk '{print $2}'

192.168.1.169What that one-liner does is filter all of the information in ifconfig by "broadcast" using grep, and then the result of that is filtered down to show us the IP address, which is in the second position on the broadcast line that was filtered first.Now, that's an awfully long command to type out every time you need to see your current IP address on the network. This is where aliasing comes in handy. Aliasing is the best part of developing an excellent Bash script.To turn a one-liner into a single-word command using aliasing, you would typealias, space, and then the simple command you want to run the one-liner. For this,ipaddressmakes sense since it's short but descriptive. Next, without a space, add an equals (=) sign. Right after that, put a double quotation mark ("), copy and paste the one-liner we just used, then add an ending double quotation mark.~# alias ipaddress="ifconfig | grep broadcast | awk '{print $2}'"HitEnterand test it out to see what you get.~# ipaddress

inet 192.168.1.169 netmask 0xffffff00 broadcast 192.168.1.255As you can see, that didn't do what we wanted, and that's because the single and double quotation marks are messing it all up. To avoid that, we can simply typeechothen put the one-liner inside parentheses with a$before the first parenthesis to indicate that everything inside the parentheses is the variable we want to be printed.~# ipaddress="echo $(ifconfig | grep broadcast | awk '{print $2}')"HitEnterand test your new alias command out again, and it should work.~# ipaddress

192.168.1.169As you can see, knowing about the $ sign to make the command run first before the result is printed got us around the issue of trying to automate the process of typing in a single word and getting your current IP address whenever it first failed.Happy Bash Scripting!This has been a brief Bash scripting intro. There a lot of stuff you can do with Bash, but in general, this is a great way to get started automating just about anything you want to do in Linux.Bash scripting is an incredibly useful skill to learn, and you don't need to know a lot about programming to duct-tape together a lot of different Linux apps and tools to make something complicated and lengthy to something easy and short.Don't Miss:How to Write Your Own Bash Script to Automate ReconWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover photo by Retia/Null ByteRelatedDon't Be a Script-Kiddie part1:Introduction to Shell ScriptHack Like a Pro:Scripting for the Aspiring Hacker, Part 1 (BASH Basics)Don't Be a Script-Kiddie part2:Building an Auto-Exploiter Bash ScriptHow To:Automate Hacking on the Raspberry Pi with the USB Rubber DuckyHack Like a Pro:Scripting for the Aspiring Hacker, Part 3 (Windows PowerShell)How To:Use LinEnum to Identify Potential Privilege Escalation VectorsHow To:Using BASH for Computer ForensicsNews:Even Microsoft Acknowledges the Superiority of the Bash Shell NowHow To:Evil-Twin (Part 1) - Setting Up the Dhcp Server.How To:Brute-Force Email Using a Simple Bash Script (Ft. THC Hydra)How To:Create a Persistent Back Door in Android Using Kali Linux:Hacking macOS:How to Steal Signal Conversations from a MacBook with a USB Rubber DuckyHow to Hack Wi-Fi:DoSing a Wireless AP ContinuouslyHow To:Get Started Writing Your Own NSE Scripts for NmapHow To:Convert video formats with Avidemux on Ubuntu LinuxHow To:A Simple Virus Written...in Bash!How To:Use predefined workflows in Microsoft Office: Mac 2008How To:Easily Find What Port a Service Runs On and Vice-VersaHack Like a Pro:How to Scan the Globe for Vulnerable Ports & ServicesHack Like a Pro:How to Hack the Shellshock VulnerabilityWeekend Homework:How to Become a Null Byte Contributor (3/2/2012)How To:Bash (Shell) Scripting for BeginnersNews:The Money Making MacroHow To:Enable Code Syntax Highlighting for Python in the Nano Text EditorNews:First Steps of Compiling a Program in LinuxHow To:Script Writing Basics How to Structure a Film Script lNews:Null Byte Is Calling for Contributors!News:Change from BASH to zshWeekend Homework:How to Become a Null Byte Contributor (3/9/2012)Goodnight Byte:HackThisSite Walkthrough, Part 6 - Legal Hacker TrainingHack Like a Pro:Hacking Samba on Ubuntu and Installing the MeterpreterHow To:Create a Custom Arch Linux DistroNews:Bind your own Hardback Book