Bash scripting is a useful and effective tool for system administration and development. It may appear extremely horrifying the first time you do it, but hopefully this guide will help relieve your anxiety.
Bash is a Unix shell, which is a command line interface (CLI) for interacting with an operating system (OS). Any command that you can run from the command line can be used in a bash script. Scripts are used to run a series of commands. Bash is available by default on Linux and macOS operating systems.
This is not intended to be a comprehensive resource to bash scripting, but rather a step-by-step guide to creating your first script and learning some basic bash syntax.
Note: Newer macOS installations (from Catalina) come installed with zsh (Z shell) as the new default, but everything in this article will still be applicable.
PREREQUISITES
- A basic command line knowledge is required.
This guide was created on macOS, and will be using /Users/you
as the default user directory for all examples. However, the concepts here will apply to any Unix-like operating system, including macOS and various Linux distributions.
Table of Content
In this tutorial, we’re going to:
- Create a bash script
- Learn about:
- Strings
- Variables
- Shell execution
- User input
- Comparison
- Conditions
- Loops
- Arrays
Create Your First Script
Making a bash script is a lot simpler than you might think.
Create a file called first-script
, using the touch
command.
$ touch first-script
Edit the file with the program of your choice. Within the file, print a string that says “My First Bash Script!’ using echo
.
echo "My First Bash Script"
Now from the command line, run the script using the bash
interpreter:
$ bash first-script
You’ll see the script has run successfully from the output.
That’s it, you’ve created your first script!
Executable Scripts
So far, you’ve learned how to run a script from the command line, prefixed with the bash
interpreter. However, if you want to run the script by name alone, it won’t work. Try to run the file simply by typing the name of the file and pressing enter. Note that we’re prefixing the file with ./
, which means a file in the current directory.
$ ./first-script
In order to run a file directly, we’ll need to change the permissions to allow the script to be executable for the user. chmod
is a command that changes permissions on a file, and +x
will add execute rights to the script.
$ chmod +x first-script
In order to interpret the file as an executable, you’ll also have to add the shebang (#!
) at the top of the script. In Unix-like systems, a text file with a shebang is interpreted as an executable file. You can confirm where the bash interpreter is located with which bash.
$ which bash
We’ll add #!/bin/bash
to the top of the script.
#!/bin/bash
echo "My First Bash Script"
Note: You may also see #!/usr/bin/env bash
instead, which can be used if you don’t know the exact path for bash.
Now you can run first-script
directly.
$ ./first-script
Note: In order to run a bash script without specifying the directory (using
./
, for example) you would have to add the directory of the script to the PATH by runningexport PATH=$PATH:/path/to/script/directory
. However, this is generally not necessary for personal scripts.
Strings
A simple string in Bash does not require double quotes – you can write it directly.
echo My first bash script
A single or double quote will expect a closing match, so in order to use one in such a string, you would need to escape the quote
echo I\'m a script
However, if you want to use a single or double quote in a string without escaping characters, you can do so by wrapping your string in quotes.
echo 'A single quoted "string"'
echo "A double quoted 'string'"
With the -e
flag, bash will interpret strings with backslash-escaped characters, such as \n
for newline. This also requires a quoted string.
echo -e "This string has a \nnew line"
Double quoted strings are also important for use with variables, as we’ll see in the next section.
Variables
A variable is declared without a dollar sign ($
), but has one when invoked. Let’s edit our my first bash script
example to use a variable for the entity being greeted, which is bash script
.
#!/bin/bash
filename="bash script"
echo "My first $filename"
Double quoted strings are required for interpolating variables. Within a single quoted string, the dollar sign would be interpreted literally
echo 'My first $filename'
Another way you might see variables written is surrounded by curly brackets along with the dollar sign, which is known as parameter expansion.
echo "My first ${filename}!"
This syntax is necessary for anything more complex you might do with a variable, such as getting one item from an array.
Shell Execution
If you would like to use the output of a shell execution within a string, you can do so with a dollar sign followed by parentheses. ($()
). For example the whoami
command will print out your current user. To use it within a string, wrap whoami
in the shell execution syntax.
echo "Hello, $(whoami)!"
User Input
We declared a variable in the last example, but we can also have the user set the value of a variable dynamically. For example, instead of just having the script say Who are you ?
, we can make it ask for the name of the person calling the script, then output that name. We’ll do this using the read
command.
#!/bin/bash
echo 'Who are you?'
read who
echo "Hello, $who!"
Comparison
Operators are slightly different in bash than what you might be used to.
In order to compare numbers, you will use the operators in the number comparison column, such as -lt
for less than.
In order to compare strings, you will use the operators in the string comparison column, such as <
for less than.
This is the opposite of what you might expect, but it’s the way it works in bash.
Number Comparison | String Comparison | Description |
---|---|---|
-eq |
== |
Equal |
-ne |
!= |
Not equal |
-gt |
> |
Greater than |
-ge |
>= |
Greater than or equal |
-lt |
< |
Less than |
-le |
<= |
Less than or equal |
You can also use -z
to test for emptiness on a string.
Conditions
if
statements use the if
, then
, else
, and fi
keywords. The condition goes in square brackets.
#!/bin/bash
echo 'How old are you?'
read age
if [ $age -gt 20 ]
then
echo 'You can drink.'
else
echo 'You are too young.'
fi
Loops
Bash uses for
, while
, and until
loops. In this example, I’ll use the for...in
loop to get all the files in a directory and list them.
#!/bin/bash
files=/Users/you/dev/*
for file in $files
do
echo $(basename $file)
done
Arrays
An array in bash is defined inside parentheses. There are no commas between the items of the array.
anime=('Naruto' 'One Pieace' 'Black Clover' 'Attack on title')
To access an item from an array, you’ll use square brackets ([]
). Arrays are 0-indexed in bash. It is also necessary to use the parameter expansion syntax.
echo ${anime[3]}
Conclusion
I hope that this article has been helpful in getting you started with bash scripting. The idea of a script having complete access to everything on my computer was initially frightening to me, but once I got used to it, I realized how useful and efficient it can be.
Read More: 5 Reasons to Use React Memo to Supercharge Performance and Boost Page Speed, Power of Webpack: A introduction and guide, Webpack Integration with React for Efficient Frontend Development, Getting Started with Regular Expressions: A Beginner’s Guide, Understanding the Difference Between REM and PX: Choosing the Right Unit for Web Design