一、變數賦值
#!/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"