Linux Shell Script
Shell script The first line is used to specify shell program #!/bin/sh Variables variable=“text” variable=0 variable=`program arguments` To use the declared variable s=“hello” echo $s echo ${s}_123 System environment variables $ export
Passing argument Special variables Number of arguments $# 1st, 2nd,.. arguments $1, $2,... Each argument =.$1..$2.... All arguments $* =.$1 $2.... Exit status $?
echo - display text or variable to stdout echo “hello” read - read from stdin read s echo “you type: $s” expr - evaluate the expression read i j=`expr $i + 10` echo $j
Shell Arithmetic Use to perform arithmetic operations. Syntax: expr op1 math-operator op2 Examples: $ expr $ expr $ expr 10 \/ 2 $ expr 20 \% 3 $ expr 10 \* 3 $ echo `expr 6 + 3`
if.- conditional statement if condition then... fi if [ “$s” = “abc” ]; then... fi Most conditions can be written by using test or [...] Test if file size > 0 -s filename Test if file exists -f filename Test file permission -r -w -x filename String equality string1 = string2 String inequality string1 != string2
Test if string length = 0 -z string Test if string length > 0 -n filename Equality i1 -eq i2 Inequality i1 -neq i2 Greater than i1 -gt i2 Greater than or equal to i1 -ge i2 Less than i1 -lt i2 Less than or equal to i1 -le i2 Negate!
Case case variable in value1)...;; value2)...;; *)...;; esac case $f in “english”) echo.hello.;; “thai”) echo.sawasdee.;; esac
While Loop while condition do... done i=0 while [ $i -lt 10]; do echo “Hello” i=`expr $i + 1` done
For Loop for variable [ in range ] do... done for f in *.txt; do cat $f done
echo command \n new line \a alert (bell) \b backspace \c suppress trailing new line \r carriage return \t horizontal tab