180 likes | 368 Views
Shell script – part 2. CS 302. Special shell variable $0 .. $9. Positional parameters or command line arguments For example , a script myscript take 2 arguments , foo and bar Using special variable, you can access your script and any parameters it has. myscript $0 foo $1 Bar $2.
E N D
Shell script – part 2 CS 302
Special shell variable $0 .. $9 • Positional parameters or command line arguments • For example , a script myscript take 2 arguments , foo and bar • Using special variable, you can access your script and any parameters it has. myscript $0 foo$1 Bar$2 $#tells you how many parameter your script was given
If condition • if condition is used for decision making in shell script, If given condition is true then command1 is executed. • Syntax: • if condition • then • command1... • fi
test expression or [ expr ] Is used to see if an expression is true Syntax: test expression OR [ expression ] • Run it as follows: • sh script.txt 3
If .. else .. fi • If given condition is true then command1 is executed otherwise command2 is executed. • Syntax: • if condition • then • command1 • else • if condition is not true then execute all commands up to fi • fi
Example (1) if [ $# -eq 0 ] then echo " Enter one argument “ exit 1 else echo " The first argument is $1 " fi
Class exercise (1) • Write a Script to see whether argument is positive or negative. First, you should ensure that a user enter an argument , if not exist and print this message “You must give/supply one integers”
# Script to see whether argument is positive or negativeif [ $# -eq 0 ]thenecho “You must give/supply one integer"exit 1fi if test $1 -ge 0thenecho "$1 number is positive"elseecho "$1 number is negative"fi
Multilevel if-then-else Syntax: if condition then condition is zero (true - 0) execute all commands up to elif statement elif condition1 then condition1 is zero (true - 0) execute all commands up to elif statement elif condition2 then condition2 is zero (true - 0) execute all commands up to elif statement else None of the above condtion,condtion1,condtion2 are true (i.e. all of the above nonzero or false) execute all commands up to fi fi
For loop Syntax: for { variable name } in { list } Do execute one for each item in the list until the list is not finished done or: for ((initial vale ; condition ;)) Do execute one for each item in the list until the list is not finished done
While loop Syntax: while [ condition ] do command1 command2 command3 .. .... done