7 unusual syntax of Linux Shell bash Programming

7 Linux Shell (bash) Programming Unusual Syntax that Can Bother

Nowadays most of the developers are working with modern programming languages like Java, C#, Ruby, Python, Scala and many more. Most of the programming languages syntax are similar to each other at least its own groups/types (static, dynamic, scripting, functional etc). One example might be Java and C#. Both have similar syntax, Ruby and Python is another example. Interesting thing is Linux Shell (bash) programming syntax has unique style which has very few similarities with other languages. Few syntax is very unusual and it creates lots of problem for developers who come from other platform. Here I explain that type of syntax.

1# Assignment Operator (=):

Almost all of the languages are used equal (=) operator as assignment operator. “Bash” has also use this. But where the point. Just keep continue the reading! In bash the correct syntax will be like:

1 x=10

If we carefully see here did not use any space before and after equal (=) operator. If we use like:

1 x= 10 or x =10  or x = 10

It will raise error. The error message will be “command not found”. But other programming languages will assign value 10 to “x” successfully. Another fact about string data. We can add any string within a variable like:

1 x=Hello
2 echo “$x” # it will print “Hello” to the console.Code language: PHP (php)

But if we try to add like:

1 #wrong assignment 2 x=Hello WorldCode language: PHP (php)

It will throw error “command not found”. So in that case we have to use:

1 x=”Hello World” or x=’Hello World’

2# Variable’s Value Set & Get:

To set any value to a variable:

1 x=10 #assign 10 to the variable “x” Code language: PHP (php)

but if we want to get value from “x” variable syntax:

1 y=$xCode language: PHP (php)

Wait! Story is not finished yet. This is not as simple as you thought. If you use $x without surrounding double quote (“$x”) you need to know more about its behavior. Suppose we write a script like:

1 dir_name=’hello world usa’
2 echo $dir_name
3 mkdir $dir_name #surprising result! Code language: PHP (php)

Guess what will be the result! Surprisingly it will create 3 directories i) hello ii) world and iii) usa. But we want to create a single directory which name will be “hello world usa”. If we want that we must use double quote (“”) when read variable value

1 dir_name=’hello world usa’
2 echo $dir_name
3 mkdir “$dir_name”Code language: PHP (php)

Similar Way if we create a file name “hello world.txt” in working directory. Later if we try to check that file existence without using double quote it print file does not exists. So in that case we should use double quote (“”) when reading variable.

1 file_name='hello world.txt' 2 # if we use $fie_name (without double quote) it will print  3 # file does not exists. Actually file is exists in working directory. 4 if [ -f "$file_name " ]; then
5 echo "file is exists" 6 else 7 echo "file does not exists" 8 fiCode language: PHP (php)

3# Conditional construct “if”:

Almost all programming language support “if” conditional construct. We use it to control our programming flow with Boolean conditions. Most of the programming language use “if” syntax like:

If ( condition) {…} or if condition or if condition then end if etc.

But bash syntax is little different. It uses square bracket as condition block. Start that block with “if” and it will end with “fi” keyword (just reverse the “if” word)

1 # it will end with “fi” keyword (just reverse the “if” word) 2 If [ x = 10 ]
3 then
4 Echo “good”
5 else 6 Echo “bad”
7 fiCode language: PHP (php)

If you mistakenly write like if[ x=10], means you did not give space in between “if” and “[“ it will throw “command not found error”. Another interesting things is if we give space after x (x =10) and do not give space before “10” it will throw error. If you add space then you have to add space between 2 operands (x = 10) otherwise you should not give any space (x=10). If we want to add multiple conditions with single if with “and” or “or” operators the syntax:

1 x=10 2 y=20 3 #if [ $x=10 ] && [ $y=2 ] # "&&" AND operator 4 if [ $x=10 ] || [ $y=2 ];then # "||" OR operator 5 echo "good" 6 else 7 echo "bad" 8 fiCode language: PHP (php)

4# Increment a Variable:

We need to do basic mathematical operation frequently. Suppose we have a variable name count. Its initial value is 1. Each time we need to add 1 with its last value. Many programming language support += operator. It means first addition 1 then assign the result. In bash we can write like:

1 count=1;
2 count+=1;
3 echo "$count"Code language: PHP (php)

Guess what “count”  value is printed on console. It will be 11. Surprised!!!

Actually it concatenate current value with new value. Without proper knowledge of this behavior it may create serious problem. If we want to see “2” is a result you can use one of the following statement:

1 let count+=1 2 let count++
3 count=$(( $count+1 ))
4 (( count=count+1 ))
5 (( count=$count+1 ))
6 (( count++ ))
7 count=`expr $count + 1`Code language: JavaScript (javascript)

5# Single Quote VS Double Quote:

Almost all cases single quote(‘) and double quote (“) works same but few cases it is different. First we should know that All characters inside single quote interpreted as string character but in double quote all characters except “$” and “`” character are single character. This 2 characters ($ and `) are expanded.

Example:

1 count=10 2 message='Count value is $count' 3 echo "$message" 4 message="Count value is $count" 5 echo "$message" 6 # First echo will display “Count value is $count’ on the console. But second echo will display “Count value is 10” 7 message='Directory exists `mkdir new_dir`' 8 echo "$message" 9 message="Directory exists `mkdir new_dir`" 10 echo "$message"Code language: PHP (php)

First echo will display “Directory exists ‘mkdir new_dir’” but second echo will display “Directory exists” then it execute mkdir command. As a result a “new_dir” directory will be created.  So before use single or double quote we have to clear our concept first.

6# Send Arguments to a Function:

Many languages use parameter variable for receive function arguments. Most of them use parameter variables (near function name) inside function parenthesis. “Bash” use parenthesis but it is not receive any argument. Instead it receive arguments from the body of the function:

1 function add(){
2  x="${1}" #first argument 3  y="${2}"#second argument 4  sum=$(( x + y ))
5 echo "$sum" 6 }
7 add 20 30Code language: PHP (php)

We just remember that function follow few conventions to receive arguments. Ist argument It will receive $1, 2nd argument it will be $2 and same order. Curly bracket “{}” use is a good practice with argument variable. If argument is more than 1 digit (suppose it would be 10) in that case we must use “${}” curly bracket. Otherwise it will throw error.

7# Value Return from a Function:

Many languages support “return” keyword for returning value from the function. Few language have convention like just statement is the return value of the function. “Bash” use “echo” statement for returning value from the function.

1 function total_amount(){
2 echo 100 3 }
4 x=$( total_amount )
5 echo "result is:$x"Code language: PHP (php)

We basically use “echo” statement to write value to the console for debug/information purpose. But here echo is used for value return purpose. If we put any debug echo inside the function it will create problem. So when we return any value from a function, we should be careful when add any debug “echo” in that function.

Feel free to leave any comments for clarification, changes, or improvements. Also, you can contact with iXora Solution expert teams for any consultation or coordination from here.

Add a Comment

Your email address will not be published. Required fields are marked *