Bash Scripting Part-2 : The How ?

Bash Scripting Part-2 : The How ?

Time Command in Bash ?

The Bash has built in time command to report how much time a process consumed. The 'time' command in Linux is used to execute a command and prints a summary of real-time, user CPU time and system CPU time spent by executing a command when it terminates.

Syntax:

time [option] [COMMAND]
time sleep 3

Variables in Bash ?

Variables are used to to store values in Linux. Variables in bash are given a value with '='. You should put no spaces before or after the =, If the value has special characters, including spaces, put the value in quotes. Example:

myvar = "this is some chars; *$\"

Reference the value of a variable with a dollar sign in front of the name. Example, echo myvar is $myvar.

export mynewvar or declare -x mynewvar.

  • You can export and assign in the same statement. For example:

      export var2="var2 value"
    
  • export -f myfunc will export the function myfunc

Working with Aliases ?

The 'alias' command instructs the shell to replace one string with another string while executing the commands. When we often have to use a single big command multiple times, in those cases, we create something called an alias for that command. Alias is like a shortcut command which will have same functionality as if we are writing the whole command.
Syntax:

alias [-p] [name[=value] ... ]

Creating an Alias:

alias name="value"

Examples:

  • alias copy = cp

  • alias rn = mv

  • alias mroe = more mroe myfile ls -l | mroe

    Creating an Unalias: Removing an existing alias is known as unaliasing.

unalias [alias name]

Echo command ?

The 'echo' command in Linux is used to display the line of text/string that is passed as an argument. This is a built-in command that is mostly used in shell scripts and batch files to output status text to the screen or a file.
Syntax :

echo [option] [string]

Displaying a text/string :

echo [string]

Options in 'echo'
1. '-n' Option: This option is used to omit echoing trailing newline.
2. '-e' Option: This enables the interpretation of backslash escapes.
3. '-E' Option: This disable backslash escaped characters in case they were enabled by default.
4. echo * would show file and directory names.

THE READ COMMAND ?

The 'read' command in Linux system is used to read from a file descriptor. Basically, this command read the total number of bytes from the specified file descriptor into the buffer. If the number or count is zero then this command may detect the errors. But on success, it returns the number of bytes read. Zero indicates the end of the file. If some errors found then it returns -1.

  • Read a line into variable or multiple variables.

  • read a b reads first word into a and rest into b.

while in Linux ?

The 'while' command in Linux is used to repeatedly execute a set of command as long as the COMMAND returns true. The test command is given and all other commands are executed till the given command’s result satisfies, when the command’s result become false, the control will be out from the while command.

Syntax:

while COMMANDS; do COMMANDS; done

Implementing while loop

c


a=0 
# -lt is less than operator 

#Iterate the loop until a less than 10 
while [ $a -lt 10 ] 
do 
    # Print the values 
    echo $a

    # increment the value 
    a=`expr $a + 1` 
done

Output:

$bash -f main.sh
0
1
2
3
4
5
6
7
8
9

What is the Pipe Operator?

In Bash, the pipe operator (|) creates a ‘pipeline’ between commands. It takes the standard output (stdout) of the command to the left and pipes it as the standard input (stdin) to the command on the right. This seamless flow of data from one command to another without the need for intermediate storage allows for the creation of efficient and compact command lines or scripts.

ls | grep 'target_file'

for Command ?

for command in Linux is used to repeatedly execute a set of command for every element present in the list.
Syntax:

for NAME [in WORDS ... ] ; do COMMANDS; done

Conditional Statements?

1. if statement
This block will process if specified condition is true.
Syntax:

if [ expression ]
then
   statement
fi

2. if-else statement
If specified condition is not true in if part then else part will be execute.
Syntax:

if [ expression ]
then
   statement1
else
   statement2
fi

Example 1: Implementing if statement.
java


#Initializing two variables 
a=10 
b=20 

#Check whether they are equal 
if [ $a == $b ] 
then 
    echo "a is equal to b"
fi 

#Check whether they are not equal 
if [ $a != $b ] 
then 
    echo "a is not equal to b"
fi

Output

$bash -f main.sh
a is not equal to b

Example 2: Implementing if.else statement
java


#Initializing two variables 
a=20 
b=20 

if [ $a == $b ] 
then 
    #If they are equal then print this 
    echo "a is equal to b"
else
    #else print this 
    echo "a is not equal to b"
fi

Output:

$bash -f main.sh
a is equal to b

Basic Operators ?

1. Arithmetic Operators: These operators are used to perform normal arithmetics/mathematical operations. There are 7 arithmetic operators:

  • Addition (+): Binary operation used to add two operands.

  • Subtraction (-): Binary operation used to subtract two operands.

  • Multiplication (*) : Binary operation used to multiply two operands.

  • Division (/) : Binary operation used to divide two operands.

  • Modulus (%) : Binary operation used to find remainder of two operands.

  • Increment Operator (++) : Unary operator used to increase the value of operand by one.

  • Decrement Operator (–): Unitary operator used to decrease the value of an operand by one.

2. Relational Operators : Relational operators are those operators which defines the relation between two operands. They give either true or false depending upon the relation. They are of 6 types:

  • ‘==’ Operator : Double equal to operator compares the two operands. Its returns true is they are equal otherwise returns false.

  • ‘!=’ Operator : Not Equal to operator return true if the two operands are not equal otherwise it returns false.

  • ‘<' Operator : Less than operator returns true if first operand is lees than second operand otherwse returns false.

  • ‘<=' Operator : Less than or equal to operator returns true if first operand is less than or equal to second operand otherwise returns false

  • ‘>’ Operator : Greater than operator return true if the first operand is greater than the second operand otherwise return false.

  • ‘>=’ Operator : Greater than or equal to operator returns true if first operand is greater than or equal to second operand otherwise returns false

3. Logical Operators : They are also known as boolean operators. These are used to perform logical operations. They are of 3 types:

  • Logical AND (&&) : This is a binary operator, which returns true if both the operands are true otherwise returns false.

  • Logical OR (||) : This is a binary operator, which returns true is either of the operand is true or both the operands are true and returns false if none of then is false.

  • Not Equal to (!) : This is a uninary operator which returns true if the operand is false and returns false if the operand is true.

Bitwise Operators : A bitwise operator is an operator used to perform bitwise operations on bit patterns. They are of 6 types:

  • Bitwise And (&) : Bitwise & operator performs binary AND operation bit by bit on the operands.

  • Bitwise OR (|) : Bitwise | operator performs binary OR operation bit by bit on the operands.

  • Bitwise XOR (^) : Bitwise ^ operator performs binary XOR operation bit by bit on the operands.

  • Bitwise compliment (~) : Bitwise ~ operator performs binary NOT operation bit by bit on the operand.

  • Left Shift (<<) : This operator shifts the bits of the left operand to left by number of times specified by right operand.

  • Right Shift (>>) : This operator shifts the bits of the left operand to right by number of times specified by right operand.

filters, head, tail and wc commands ?

Filters

In UNIX/Linux, filters are the set of commands that take input from standard input stream i.e. stdin, perform some operations and write output to standard output stream i.e. stdout. The stdin and stdout can be managed as per preferences using redirection and pipes. Common filter commands are - grep, more, sort.

  • Filters can be used in pipes.

  • Filters provide the powerful means of combining the input and output of a sequence of commands to get the kind of report you want.

head

It displays the first n lines of the specified text files. If the number of lines is not specified then by default prints first 10 lines.
Syntax:

head [-number_of_lines_to_print] [path]

tail Command

It works the same way as head, just in reverse order. The only difference in tail is, it returns the lines from bottom to up.
Syntax:

tail [-number_of_lines_to_print] [path]

wc Command

The 'wc' command gives the number of lines, words and characters in the data.
Syntax:

wc [-options] [path]

Conclusion

In Bash, various commands and constructs enhance scripting efficiency. The 'time' command measures process execution time, while variables store values and aliases offer shortcut commands. Echo displays text, read reads from file descriptors, and while loops execute commands based on conditions. Pipes connect command outputs, and 'for' loops iterate over lists. Conditional statements control flow, and basic operators perform arithmetic and logical operations. Filters like grep and sort manipulate input, while head, tail, and wc analyze text data, collectively offering powerful tools for command-line tasks.