iXora Custom Software Development Blog

Read | Practice | Advance

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

Posted by on in Blog
  • Font size: Larger Smaller
  • Hits: 2439
  • 0 Comments

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:

x=10

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

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:

x=Hello
echo “$x” # it will print “Hello” to the console.

But if we try to add like:

#wrong assignment
x=Hello World

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

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

2# Variable’s Value Set & Get:

To set any value to a variable:

x=10 #assign 10 to the variable “x”

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

y=$x

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:

dir_name=’hello world usa’
echo $dir_name
mkdir $dir_name #surprising result!

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

dir_name=’hello world usa’
echo $dir_name
mkdir “$dir_name”

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.

file_name='hello world.txt'
# if we use $fie_name (without double quote) it will print 
# file does not exists. Actually file is exists in working directory.
if [ -f "$file_name " ]; then
   echo "file is exists"
else
   echo "file does not exists"
fi

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)

# it will end with “fi” keyword (just reverse the “if” word)
If [ x = 10 ]
then
      Echo “good”
else
     Echo “bad”
fi

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:

x=10
y=20
#if [ $x=10 ] && [ $y=2 ] # "&&" AND operator
if [ $x=10 ] || [ $y=2 ];then # "||" OR operator
   echo "good"
else
   echo "bad"
fi

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:

count=1;
count+=1;
echo "$count"

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:

let count+=1
let count++
count=$(( $count+1 ))
(( count=count+1 ))
(( count=$count+1 ))
(( count++ ))
count=`expr $count + 1`

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:

count=10
message='Count value is $count'
echo "$message"
message="Count value is $count"
echo "$message"
# First echo will display “Count value is $count’ on the console. But second echo will display “Count value is 10”
message='Directory exists `mkdir new_dir`'
echo "$message"
message="Directory exists `mkdir new_dir`"
echo "$message"

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:

function add(){
  x="${1}" #first argument
  y="${2}"#second argument
  sum=$(( x + y ))
  echo "$sum"
}
add 20 30

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.

function total_amount(){
  echo 100
}
x=$( total_amount )
echo "result is:$x"

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.

Rate this blog entry:
2

Comments

  • No comments made yet. Be the first to submit a comment

Leave your comment

Guest
Guest Tuesday, 11 August 2020