shell要点
1、
for file in `ls /etc` do echo $file done
2、变量赋值单引号内变量不变换,转义字符无效
双引号可以变换
your_name='qinjx' str="Hello, I know your are $your_name! \n"
字符串长度echo
${
#str}
提取子字符串echo
${str:1:4}
#输出ello
3、数组
array_name=(value0 value1 value2 value3) array_name[0]=value0 array_name[1]=value1 array_name[n]=valuen 读取元素 valuen=${array_name[n]} # 取得数组元素的个数 length=${#array_name[@]} # 或者 length=${#array_name[*]} # 取得数组单个元素的长度 lengthn=${#array_name[n]}
4、test 数值测试
exampe
num1=100 num2=100 if test $[num1] -eq $[num2] then echo 'The two numbers are equal!' else echo 'The two numbers are not equal!' fi
字符串测试
文件测试
5、流程控制
if condition1 then command1 elif condition2 command2 else commandN fi
COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER='expr $COUNTER+1' echo $COUNTER done
echo 'Input a number between 1 to 4' echo 'Your number is:\c' read aNum case $aNum in 1) echo 'You select 1' ;; 2) echo 'You select 2' ;; 3) echo 'You select 3' ;; 4) echo 'You select 4' ;; *) echo 'You do not select a number between 1 to 4' ;; esac
6、函数
#!/bin/bash funWithParam(){ echo "The value of the first parameter is $1 !" echo "The value of the second parameter is $2 !" echo "The value of the tenth parameter is $10 !" echo "The value of the tenth parameter is ${10} !" echo "The value of the eleventh parameter is ${11} !" echo "The amount of the parameters is $# !" echo "The string of the parameters is $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73
输出为
The value of the first parameter is 1 ! The value of the second parameter is 2 ! The value of the tenth parameter is 10 ! The value of the tenth parameter is 34 ! The value of the eleventh parameter is 73 ! The amount of the parameters is 12 ! The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
参数处理:
6,shell算术表达式
declare
不支持浮点数,需要bc,awk支持
$[ ]
$(( ))
let
$(expr )
7、处理命令行参数
option = $(getopt -o -l)