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.
Requirements
To follow along, all you'll need is an Ubuntu or Kali Linux system. 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 a Raspberry Pi or another single-board computer to run a Linux build on.
- On Amazon: Great Deals on Raspberry Pi Bundles
Step 1: Find You Bash Interpreter
To get started, we need to know which Bash interpreter we're using. To do so, use which bash in a terminal window. Learning the location of the interpreter will be useful when writing our first Bash script.
~# which bash
usr/bin/bash
Step 2: Make Your First Bash Script
To 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.sh
In the document, start the first line with a shebang (#!) followed by the location of your Bash interpreter (for me, it's usr/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/bash
Let's create a variable to make something happen. For something simple, we'll just use a STRING that says Null Byte. You could make it say whatever you want.
STRING="Null Byte"
Now we want to echo something 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 hitting Control-X on your keyboard to exit, then Y to save the modified buffer, and then Enter to save the file. This will bring you back to the terminal window. To test out the script, use bash 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 Byte
Step 3: Use Positional Variables
Let'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 says echo "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 of bash bash.sh before 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 with Control-X, then Y, then Enter, and you'll be back at the terminal window. To test out the script, use bash 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 president
Each 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 Output
Next, 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. After echo, 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 like ifconfig, but to make it easy, we're going with whoami, 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 with Control-X, then Y, then Enter, then test out the script with bash 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
root
Step 5: Take User Input
So what about interactivity? Bash scripting has that down as well. Open the bash.sh file 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 use echo to print to the user "What is your name?" Then, on the next line, we'll add a variable of name with the read command. Whatever they input after being asked the question will be seen by our program. To use the variable, let's use echo to print a statement about the name they inputted. The statement uses $name to 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 with Control-X, then Y, then Enter, then test out the script with bash 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 hit Enter, 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 punk
We'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 Statements
Let's try something a little more advanced, which are if statements. 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 the bash.sh script and change a few things.
If we want to see whether or not the user has actually input a name, we can use an if statement. This is a pretty typical example. So let's keep the first echo line where it is, as well as the read line. But let's swap out the second echo command with different echo lines for if and else.
Use if followed by a space, then add a pair of brackets. Inside those brackets, put the variable name with spaces on each side of it. If you skip the spaces, you'll get an error. Afterward, type a semicolon (;), another space, and then for the ending. On the next line, indent and put an echo statement. 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 hits Enter to skip the question? On the next line, put else in, and that's it. On the following line, indent and add another echo printout. 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 the fi command, which just says that the script is finished. Without this, you'll get errors because when you have loops such as an if statement, 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"
fi
If 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"
fi
Save your script again with Control-X, then Y, then Enter, then test out the script with bash 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 me
However, if you just hit Enter without 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 me
Having 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 Commands
I'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 like ifconfig to get a whole lot of information about the computer's interface parameters. To narrow it down, you could pipe it into grep and target more specific information. So ifconfig | grep broadcast is a good example.
~# ifconfig | grep broadcast
inet 192.168.1.169 netmask 0xffffff00 broadcast 192.168.1.255
Above, 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 by awk '{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.169
What 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 type alias, space, and then the simple command you want to run the one-liner. For this, ipaddress makes 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}'"
Hit Enter and test it out to see what you get.
~# ipaddress
inet 192.168.1.169 netmask 0xffffff00 broadcast 192.168.1.255
As 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 type echo then 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}')"
Hit Enter and test your new alias command out again, and it should work.
~# ipaddress
192.168.1.169
As 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.
Just updated your iPhone to iOS 18? You'll find a ton of hot new features for some of your most-used Apple apps. Dive in and see for yourself:
Be the First to Comment
Share Your Thoughts