Operators in linux shell scripting

There are lot of interesting operators in shell scripting that you don’t find in other languages.
  • Arithmetic
  • Relational
  • Logical
  • File

Arithmetic operators

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

Relational operators

In relational operators, we have below operators. -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 [ ] 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.
  • &&
  • ||

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.
  • -d : We can use this option to check for directory existence.
  • -G : This option is used to check if file is owned by specific group.
  • -r : This option is used to check there is read permission on file. Exit status is 0 if read permission is available.
  • -s : This option is used to check if size of file is not 0. Exit status is 0 if size of file not zero.
  • -w : This option is used to check there is write permission on file. Exit status is 0 if write permission is available.
  • -x : This option is used to check there is execute permission on file. Exit status is 0 if execute permission is available.

Web development and Automation testing

solutions delivered!!