Friday, September 11, 2009

Linux - Shell - scripts

Each shell scripts should start as following:

#!/bin/bash

Variables
There are three kinds of variables:
- special variables;
- environment variables;
- application's variable.

Special varibles
Provider information about some process.

$# - list of arguments
$0 - name of shell scripts
$1, $2,... - script's parameters
$* - list of parameters pass to the script ("$1 $2 ...")
$@ - list of parameters ("$1" "$2" ...)
$$ - gets PID of the current process
$? - returns code of the last run process
$! - returns PID of invoked process

Application's variables
Application's variable are typeless although you can create it by declare function. Variables can be declared anywhere in a shell script as was shown below:

waldekd@waldekd-laptop:~$ v="VARIABLE"
waldekd@waldekd-laptop:~$ echo $v
VARIABLE


Arrays
We can use only one dimensional arrays by declaring it in one of shown ways:

waldekd@waldekd-laptop:~$ tab={el1,el2}
waldekd@waldekd-laptop:~$ tab[1]={el3}
waldekd@waldekd-laptop:~$ declare -a tab
waldekd@waldekd-laptop:~$ echo ${tab[1]}
{el3}
waldekd@waldekd-laptop:~$ echo ${tab[*]} --> returns "elem_1 elem_2 elem_3"...
waldekd@waldekd-laptop:~$ echo ${tab[@]} --> returns "elem_1" "elem_2" "elem_3"...


You can undeclare an array's element by using unset command:

waldekd@waldekd-laptop:~$ unset tab[1]
waldekd@waldekd-laptop:~$ unset tab[*]
waldekd@waldekd-laptop:~$ unset tab[@]


Array length is available with the following command:

waldekd@waldekd-laptop:~$ echo ${tab[*]}

We cal also use systems' commands:

#!/bin/bash
command=$(pwd)
echo "Current directory is $command"


Evaluating of arithmetical expressions

To evaluate of arithmetical expression you can use let command:

#!/bin/bash
a=10
b=5
let sum=a+b
echo $sum


or double brackets

#!/bin/bash
a=10
b=5
sum=$(( a+b ))
echo $sum


or square brackets

#!/bin/bash
a=10
b=5
sum=$[ a+b ]
echo $sum

No comments:

Search This Blog