08-12-2023, 09:17 AM
Basic Bash Commands for Your First Bash Script
In order to successfully create your first bash script, you need to understand the essential bash commands. They
are the main elements of a script, and you must know what they do and how to write them properly.
There are a lot of bash commands on Linux. To start things off, we’ll cover seven basic ones.
1. Comments
Comments feature a description on certain lines in the script. The terminal doesn’t parse comments during
execution, so they won’t affect the output.
There are two ways to add comments to a script. The first method is by typing
# at the beginning of asingle-line comment.
#!/bin/bash
# Command below prints a Hello World text
echo "Hello, world!"
The second method is by using
: followed by '. This method works for multiple-line comments.#!/bin/bash
read a
: '
The following commands prints
Hello, world!
'
echo "Hello, World!"
2. Variables
Variables are symbols that represent a character, strings of characters, or numbers. You only need to type the
variable name in a command line to use the defined strings or numbers.
To assign a variable, type the variable name and the string value like here:
testvar="This is a test variable"
To read the variable value in the command line, use the
$ symbol before the variable name. Take a look at theexample below:
#!/bin/bash
testvar="This is a test variable"
echo $testvar
3. echo Command
echo is a well-known command used in many programming languages. There are various options you can use with echoto print the output on the terminal.
The first and most common use of
echo is to output standard text:#!/bin/bash
echo "Hello, world!"
The output of that command is Hello, World! By default, when using the
echo command like this, the terminal will input a new line underneath that. If you want to echo an output without a new line, you can do so by using -n.#!/bin/bash
echo -n "Hello, world!"
Use the option
\n to introduce a line break into the output. To enable the backslash (\), you need to include -e.#!/bin/bash
echo -e "Hello, \nworld!"
The option
\t adds a horizontal tab space:#!/bin/bash
echo -e "\tHello, world!"
This command’s output will indent the text to the right:
Hello, world!
You can also combine several options. For example, combine
\n and \t to break the text into lines and indent it to the right:#!/bin/bash
echo -e "\n\tHello, \n\tworld!"
The output of that command will look like this:
Hello,
world!
4. Functions
A function compiles a set of commands into a group. If you need to execute the command again, simply write the function instead of the whole set of commands.
There are several ways of writing functions.
The first way is by starting with the function name and following it with parentheses and brackets:
function_name () {
first command
second command
}
Or, if you want to write it in a single line:
function_name () { first command; second command; }
The second method to write a function is using the reserved word
function followed by the function name. This eliminates the need for parentheses:
function function_name {
first command
second command
}
This method also has a single-line version:
function function_name { first command; second command; }
For example, we can write two functions with multiple
echo commands:#!/bin/bash
hello_world () {
echo "Hello, World!"
echo "This is a test function"
}
print_message () {
echo "Let’s learn bash programming"
echo "Enjoy this tutorial"
}
Note that writing the functions as in the example above only defines them and doesn’t execute the contained commands. To execute a function, enter its name into the command line.
Now, let’s use the two examples above in a complete bash function, including its execution:
#!/bin/bash
# Define a hello world function
hello_world () {
echo "Hello, World!"
echo "This is a test function"
}
# Define a print message function
print_message () {
echo "Let’s learn bash programming"
echo "Enjoy this tutorial"
}
# Execute the hello world function
hello_world
# Execute the print message function
print_message
This is the output of the script above:
Hello, World!
This is a test function
Let’s learn bash programming
Enjoy this tutorial
5. Loops
Loop bash commands are useful if you want to execute commands multiple times. There are three types of them you can run in bash –
for, while, and until.The
for loop runs the command for a list of items:#!/bin/bash
for item in
- do
[commands]
done
The following example uses aforloop to print all the days of the week:
#!/bin/bash
for days in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
do
echo "Day: $days"
done
On line 2, "days" automatically becomes a variable, with the values being the day names that follow. Then, in theechocommand, we use the$symbol to call the variable values.
The output of that script will be as follows:
Day: Monday
Day: Tuesday
Day: Wednesday
Day: Thursday
Day: Friday
Day: Saturday
Day: Sunday
Notice that even with just one command line in the loop script, it prints out sevenechooutputs.
The next type of loop iswhile. The script will evaluate a condition. If the condition is true, it will keep executing the commands until the output no longer meets the defined condition.
#!/bin/bash
while [condition]
do
[commands]
done
Let’s take a look at a simple example that involves a variable and increment operator, denoted as((++)):
#!/bin/bash
i=0
while [ $i -le 5 ]
do
echo $i
((i++))
done
The variable starts with a 0 value, and the increment operator will increase it by one. The condition set is less than or equal to five, so the command will keep iterating until the output reaches five. The output of that script will be as follows:
0
1
2
3
4
5
The last type of loop,until, is the opposite ofwhile. It will iterate the command until the condition becomes true.
If we want the same output as thewhileexample above using theuntilloop, we can write the script like this:
#!/bin/bash
i=0
until [ $i -gt 5 ]
do
echo $i
((i++))
done
Now, this command will iterate until the output value reaches five. The output will be the same as our example with thewhileloop:
0
1
2
3
4
5
6. Conditional Statements
Many programming languages, including bash, use conditional statements likeif,then, andelsefor decision-making. They execute commands and print out outputs depending on the conditions.
Theifstatement is followed by a conditional expression. After that, it’s followed bythenand the command to define the output of the condition. The script will execute the command if the condition expressed in theifstatement is true.
However, if you want to execute a different command if the condition is false, add anelsestatement to the script and follow it with the command.
Let’s take a look at simpleif,then, andelsestatements. Before the statement, we will include a variable so the user can input a value:
#!/bin/bash
echo "Enter a number"
read num
if [[ $num -gt 10 ]]
then
echo "The number is greater than 10"
else
echo "The number is not greater than 10"
7. Reading and Writing Files
There are several methods to read a file, with thecatcommand being the most popular one. Note that this command reads the whole file content.
To read the content line by line, use thereadcommand and a loop. Before writing a script to read a file, make sure that the file exists first.
In the following example, we have ato-do.txtfile that contains a to-do list:
Reply email
Finish report
Call clients
Team evaluation
We’ll use thecatandreadcommands in our bash function to read and print the content of theto-do.txtfile. The first part of the script will use thecatcommand, while the second part will use thereadcommand in a loop.
#!/bin/bash
echo "Reading the file using cat command"
content='cat to-do.txt'
echo $content
echo "Reading the file using read command and loop"
filename='to-do.txt'
while read line
do
echo $line
done<$filename
The output of the script will be as follows:
Reading the file using cat command
Reply email Finish report Call clients Team evaluation
Reading the file using read command and loop
Reply email
Finish report
Call clients
Team evaluation
To write a command output into a file, use the redirection operators, represented with the>and>>symbols, and follow them with the file name:
output > filename
output >> filename
Be careful when choosing the operator. If the file exists, the>operator will overwrite its content with a zero-length string. It means you’ll lose the existing file content. If the inputted file name doesn’t exist, it will create it.
The>>operator, on the other hand, will add the output to the given file.
Here’s a simple redirection to write the output into a text file:
echo "Hello, world!" >> hello_world.txt
Redirection also works with thereadcommand to write any user input. This script example will add the input value into thename.txtfile:
#!/bin/bash
echo "Enter your name"
read Name
echo $Name >> name.txt
Because the script redirects the variable output into the file, you won’t see any output printed. To see the output by printing the file content, add the following command line to read the file:
echo 'cat name.txt'
Make sure that you have the permission to read and write in the file to prevent the permission denied error. If you want to add the output to existing files, make sure to type in the correct file names.

