User Tools

Site Tools


wiki:bashscript

Bash script

Setting Variables

Any programming language needs variables.
You define a variable as follows:

x=home

never insert space before and after the =.
You recall the x variable by using $x

echo $x

A variable can be the results of a command included in backquote ():
Example:

y=`ls`
echo $y

Another way to retrieve the result of a command is to insert the command between $(ls) rather ls

y=$(ls)
echo $y

So x it will be the list of the file stored in the directory where you are working.
You can also use the variable in the command options:

grep $x file.txt   

It will search the word home in file.txt

Flow Control Statements

The for loop

The syntax of for loop is
for var in wordlist do
    command(s)
done
The command(s) is executed once for each word (or item) in the wordlist, and each time the variable var contains the value of that word.

for i in a b c d f ; do
     echo the value of i is $i
done

in one line you can write:

for i in a b c d f ; do  echo the value of i is $i ; done

The wordlist can be also numberlist and You can use also the result of a command to create the wordlist or numberlist:

for i in `seq 1 5` ; do
     echo the value of i is $i
done


For numerical sequences this syntax is often used:
for ( (i=number; i<number; i++ ) ) ; do
    command(s)
done

The command(s) is executed once for each number in the numberlist, and each time the variable var contains the value of that number.

for ((i=1; i<10; i++ )) ; do
     echo the value of i is $i
done

in one line you can write:

for ((i=1; i<10; i++ )) ; do   echo the value of i is $i ; done

The for while loop

In this course the while loop will not be used, but you can easily find it on the web, just google: The while loop bash

The if... then condition

The syntax of if … then is:
if [expression]; then
   code if 'expression' is true.
fi
The code to be executed if the expression within braces is true can be found after the 'then' word and before 'fi' which indicates the end of the conditionally executed code.
Example:

x=tree
if [ $x = "tree" ]; then
echo x is equal tree 
fi

The if...then...else condition

The syntax of if … then ….else is:
if [ expression ]; then
   code if 'expression' is true
else
   
code if 'expression' is not true
fi
Example:

x=tree
if [ $x = "tree" ]; then
echo x is equal tree 
else
echo x is not equal to tree
fi

The if...then... condition inside a for loop

A very common example is an if condition inside a for loop.
Example:

for ((i=1; i<10; i++ )) ; do 
if [ $i != 3  ]; then
     echo the value of i is $i
fi
done

Get help in the if...then... condition

To search for the different settings and statements of the if condition:

man test
wiki/bashscript.txt · Last modified: 2017/12/05 22:53 (external edit)