DEV Community

Cover image for Bash scripting guide
Anton Sakhanovych
Anton Sakhanovych

Posted on

Bash scripting guide

What is shebang?

Shebang is a line that starts with #! to specify the interpreter of the script!

Note: Shebang is not specific to the bash scripting!

Usual shebang for the bash scripts looks like this:#!/bin/bash. However, be careful! Because different linux distributions can have different paths to bash executable. You can check yours by typing which bash into console. Mine path, for example, is /usr/bin/bash. The portable shebang that will work on any linux distribution looks like this: #!/usr/bin/env bash This way the script will look for the path of bash executable using env command.

Hello World!

Now let's write the hello world script!

#!/usr/bin/env bash

echo "Hello World!"
Enter fullscreen mode Exit fullscreen mode

Variables

Variables are pretty straight-forward in bash. You create variable like this: name="Anton". There should be no spaces on both sides of the equal sign! To refer to the variable you use $. For example: echo $name would print out Anton. You can even embed variables in strings: echo "My name is $name" will print out My name is Anton. Also, you cannot use single quotations marks to wrap the string! This will work differently echo 'My name is $name' This will print out: My name is $name because single quotation marks interpret everything as string.

Basic math

Basic math in bash is nothing like in other languages.
if you type 5 + 5 in the console it will give you this error: bash: 5: command not found because bash is looking for command to execute but it's not there. Following this logic that the bash needs a command to execute, you might say that there should be a command that does math. And you would completely correct. The command for basic math is expr. The usage: expr 5 + 5. The spaces between arguments are important! If you try to run expr 5 +5, it will give you an error: expr: syntax error: unexpected argument β€˜+5’

If statements

If statements are also quite different compared to other languages. It doesn't have =, <, >, >=, <= operators. Instead you write your condition in square brackets like this [$num -eq 1]. Under the hood bash uses command called test You can use man pages to learn more. The basic comparison operators are -eq, -gt, lt, -ge, -le, -ne. The example script:

#!/usr/bin/env bash

age=18
if [ age -eq 18 ]
then
    echo "He is $age years old"
fi
Enter fullscreen mode Exit fullscreen mode

This will print out: He is 18 years old

Exit codes

Exit codes are useful when scripting! You can check whether previous command was successful. You use variable $? to check the exit code of the previous command. The general rule for exit codes is that if exit code is not 0 it means that you got an error. If you run ls and then echo $? you will get 0 because the execution of ls was successful. However, if you run ls /nonexistent and then echo $? it will give you 2.

While Loops

While loops are pretty easy too! Combine if statement with while and you get this

num=0
while [ $num -le 5 ] 
do
    #printing the number
    echo "$num"
    # adding one each iteration
    num=$(expr $num + 1)
done
Enter fullscreen mode Exit fullscreen mode

You will get this:

0
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

For Loops

For loops are just as easy:
Example script:

for n in {1..5}
do
    echo $n
done
Enter fullscreen mode Exit fullscreen mode

You will get:

1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Data Streams

Data streams is the way to redirect standard output(stdout) and standard err(stderr). Use1> to redirect stdout. ls 1> output.txt After running this you will be able to find the result of the execution of this command in the file named output.txt. However all the errors will still be printed out on the screen. You can use 2> to catch any errors and send them to file. And similarly &> to redirect both stdout and stderr.

Functions

Syntax for function:

function_name(){
    echo "Parameter #1 is $1"
}

function_name 3
Enter fullscreen mode Exit fullscreen mode

Output: Parameter #1 is 3

Note that when you call a function you don't have parenthesis around the arguments you separate them with spaces.

Also you can see that you can refer to parameters using $ and the number of the argument. In this case that would be $1 to refer to the first positional argument!

Case Statements

Case statements! Just make sure that you put double semi-colon in the end of each case! The * case is just the default behavior in case your variable doesn't match any of the previous cases!

case $variable in
   case1) instructions;;
   case2) instructions;;
   case3) instructions;;
   case4) instructions;;
   case5) instructions;;
   *) default behavior;;
esac
Enter fullscreen mode Exit fullscreen mode

Arguments

Just like in functions you can access arguments that you passed while calling a function. For example:

name=$1
echo $name
Enter fullscreen mode Exit fullscreen mode

if you call this script: script.sh Anton

It will print out Anton

Also very handy variable: $# which contains the total number of arguments. For the script call above the $# would equal to 1 because we passed only one argument Anton.

This article is inspired by series on youtube: Bash Scripting Series by Learn Linux TV

Thanks for reading this article! And the further exploration of bash scripting is highly encouraged!

Top comments (0)