Friday, February 1, 2013

Bash Conditionals

Conditionals are used when you must make some decision (to execute some part of code or not) by evaluating expression in your script.
For conditionals in Bash scripting language are used clauses: if, then, else.

if (some expression)
then
(do some code)
else
(do some code)

Simplest example is use only if,then

if ["$Var1" = "$Var2"]; then
echo "Variables Var1 and Var2 are equal!"
fi

with clause fi we close if statement.

Other example:

if ["$Var1" = "$Var2"]; then
echo "Variables Var1 and Var 2 are equal!"
else
echo "Variables Var1 and Var2 are NOT equal!"
fi


Variables in Bash script

Variables in Bash script language have following properties:
  • They haven't data type
  • There is no need to declare variable
So, let's see how they works on simple "Hello World" Example:
#!/bin/bash
Var1 = "Hello World!"
echo $Var1
This simple example will output sentence Hello World!

 Interesting with $ sign in Bash is, if you put something in brackets after $ this will be interpreted as interpreter command.
#!/bin/bash
Var1= $(ls -la)
echo $Var1
This simple example will put output from ls -la command in $Var1 variable and then print content on screen.

Important thing about variables is that you can use local variables in functions, using keyword local.

local Var1="Local variable"

Builtin variables

 

 Bash have Built-in variables, some of them are:
  • $BASH - Path to the Bash binary
  • $BASHPID - Process ID of Bash 
  • $BASH_VERSION - Version of Bash
  • $HOME - Home directory of user
  • $MACHTYPE - Machine type
  • $PATH - Path to binaries
  • $PWD - Working directory
  • $SECONDS - number of second while script is running
  • $UID - User ID number
  • $0,$1 ... - Command line arguments
  • $# - Number of command line arguments
And many more...