Scripting Imp rules

1. Command Substitution:

old style: `command`

new style: $(command) -> Recommanded

Eg: echo "Todays date is: `date +%D`"

       echo "Todays date is:$(date +%D)"

2. variable substitution

$variable name

${variablename} -> Recommanded



Never use single quoates for variable substitution

Eg: echo '$NAME'

ouput: $NAME

3.Arihmetic operations:

We can perform arthemetic operations using 4 ways:

2 nd method is not used mostly

Example:


Note(VVIMP): Except assignment operator, for all operators we should provide space before and after operator

Eg: If we provide space after assignment operator, it would result in error
add_result = `expr $a + $b` (Invalid)
add_result=`expr $a + $b` (valid, Since no spave before and after = operator)

4.Assignment and comparison:

x=10 -> Assignment(No space)
x = 10 -> comparison(space)

Eg: There is space before and after =, so it is comparison
#!/bin/bash
read -p "Enter you name:" name

if [ $name = "bhuvan" ]; then
echo "Hi bhuvan .. Good Morning"
else
echo "Hi, How are you $name"
fi

5. Command line arguments:






6. Terinary operator(The name I used to call)

From my experience I use the && and || to reduce an if statement to a single line.

Say we are looking for a file called /root/Sample.txt then the traditional iteration would be as follows in shell:

if [ -f /root/Sample.txt ]
then
    echo "file found"
else
    echo "file not found"
fi

These 6 lines can be reduced to a single line:

[[ -f /root/Sample.txt ]] && echo "file found" || echo "file not found"

When running a few iterations to set variables or to create files etc., life is easier and the script looks slicker using the single line if function, it's only drawback is that it becomes a bit more difficult to implement multiple commands from a single iteration however you can make use of functions.


7. File Test options:

8. String Test options:
9.Different mehods to perform incement:

Different methods to perform incremental operation in bash

Here there is a consolidated list of methods which you can choose based on your shell and environment to increment a variable. In the above script where I have used ((failed++)) or LINE=$(($LINE+1)), just replace this with any of the methods from the below table.

NumberIncremental Variable
1var=$((var+1))
2var=$((var++))
3((var=var+1))
4((var+=1))
5((var++))
6((++var))
7let "var=var+1"
8let "var+=1"
9let "var++"
10let var=var+1
11let var+=1
12let var++
13declare -var var; var=var+1
14declare -var var; var+=1
15var=$(expr $var + 1)
16var=`expr $var + 1`

9. Access array elements:

10. Function with parameters:

11. Export in bash
blog here

Comments