Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic Bash Commands
#1


    Basic Bash Commands for Your First Bash Script

   

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 a
        single-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 the
        example 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 echo
        to 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 a for loop 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 the echo command, 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 seven echo outputs.

    The next type of loop is while. 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 of while. It will iterate the command until the condition becomes true.

    If we want the same output as the while example above using the until loop, 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 the while loop:

   
0
1
2
3
4
5
   

   

6. Conditional Statements


    Many programming languages, including bash, use conditional statements like if, then, and else for decision-making. They execute commands and print out outputs depending on the conditions.

    The if statement is followed by a conditional expression. After that, it’s followed by then and the command to define the output of the condition. The script will execute the command if the condition expressed in the if statement is true.

    However, if you want to execute a different command if the condition is false, add an else statement to the script and follow it with the command.

    Let’s take a look at simple if, then, and else statements. 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 the cat command being the most popular one. Note that this command reads the whole file content.

    To read the content line by line, use the read command and a loop. Before writing a script to read a file, make sure that the file exists first.

    In the following example, we have a to-do.txt file that contains a to-do list:

   
Reply email
Finish report
Call clients
Team evaluation
   

    We’ll use the cat and read commands in our bash function to read and print the content of the to-do.txt file. The first part of the script will use the cat command, while the second part will use the read command 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 the read command to write any user input. This script example will add the input value into the name.txt file:

   
#!/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.

   

   

Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)