Operators in linux shell scripting

There are lot of interesting operators in shell scripting that you don’t find in other languages.

  1. Arithmetic
  2. Relational
  3. Logical
  4. File

Arithmetic operators

In arithmetic operators, we have +, – , /, *, %, =  etc.

Relational operators

In relational operators, we have below operators.

  1. -lt (less than), -gt(greater than), -le(less than or equal to), -ge(greater than or equal to), -eq (equal to), -ne (not equal to). We should use these operators in [ ]
  2. We also have <, >, <=, >=, == and != operators. We should use these operators with double square brackets [[ ]]

[[ ]] is an extension of []. Double brackets are not POSIX complaint. So you should use it carefully as same script may not work on all other shells.

operators-in-linux-bash-scripting

operators-in-linux-bash-scripting

Below examples show how to compare string in Linux. Here “-n” means not empty. “-z” means empty string.

string-comparison-in-linux

string-comparison-in-linux

Logical operators

We have below logical operators.

  1. &&
  2. ||

File Operators

In file operators, we have lot of operators that allow us to check if file is read only, executable or empty etc.

To check if file exists, you can use below command.

[[ -e f1.txt ]]

Above command has an exit status as 0 if file “f1.txt” exists.

We can use many options as mentioned below to check various attributes of a file.

  1. -d : We can use this option to check for directory existence.
  2. -G : This option is used to check if file is owned by specific group.
  3. -r : This option is used to check there is read permission on file. Exit status is 0 if read permission is available.
  4. -s : This option is used to check if size of file is not 0. Exit status is 0 if size of file not zero.
  5. -w : This option is used to check there is write permission on file. Exit status is 0 if write permission is available.
  6. -x : This option is used to check there is execute permission on file.  Exit status is 0 if execute permission is available.

You may also like...