一、变量赋值
#!/bin/bash
a="hello world" # = 两侧不能有空格!
echo "a is $a"
unset a
echo "this is ${a}nd" #变量最好用 {} 扩起来,避免混淆
declare -i num1=10
declare -i num2=20
declare -i num3=$num1+$num2
比较重要的命令:
ls wc cp mv grep cut cat file read sort uniq expr find tee basename dirname head tail sed awk
二、流程控制
1.参数控制
#!/bin/bash
echo $1 $2 #参数名
echo $0 #程序名
echo $@ #在一个变量中列出所有参数 $*
echo $# #参数个数
echo $$ #进程号
echo $? #上一条单独命令的退出状态
2.if 循环(各参数一定要用空格隔开!!)
#!/bin/bash
for day in 1 2 3 4 5 6 7
do
if [ $day = 6 -o $day = 7 ]
then
echo "$day is a nice day"
elif [ $day = 1 ]
then
echo "starting to work..."
fi
done
3.case
read -p 'Please input a num: ' num
case $num in
1)
echo 1;;
2)
echo 2;;
3 | 4)
echo 3 or 4;;
*)
echo 'other';;
esac
4.for
#!/bin/bash
read dir
if [ -d "$dir" -a -r "$dir" ]; then
file=$(ls $dir)
for filename in $file
do
if [ -u "$dir/$filename" ]; then
echo "$filename has uid"
ls -l "$dir/$filename"
fi
done
else
echo "sorry $dir does not exist or could not read"
fi
此例可输入: /usr/bin
5.while
#!/bin/bash
read str
while [ "$str" != 'ubuntu' ]
do
echo 'not right'
read str
done
echo "you have guessed it !"
6.until
#!/bin/bash
read str
until [ $str = 'quit' ]
do
echo 'keep on'
read str
done
printf "you have entered quit !\n"