- 基礎語法
- 文件頭必須要有
#!/bin/sh
- shell腳本里盡量使用絕對路徑
- 使用
.sh
結尾
#!/bin/sh #This is to show what a example looks like. echo "My First Shell!" echo "This is current directory." # 展示當前路徑 /bin/pwd echo echo "This is files." # 列出當前路徑下的文件或文件夾 /bin/ls
#!/bin/sh /bin/date +%F >> /test/shelldir/ex2.info echo "disk info:" >> /test/shelldir/ex2.info /bin/df -h >> /test/shelldir/ex2.info echo >> /test/shelldir/ex2.info echo "online users:" >> /test/shelldir/ex2.info /usr/bin/who | /bin/grep -v root >> /test/shelldir/ex2.info echo "memory info:" >> /test/shelldir/ex2.info /usr/bin/free -m >> /test/shelldir/ex2.info echo >> /test/shelldir/ex2.info #將上面收集的信息發送給root用戶,并且刪除臨時文件 /usr/bin/write root < /test/shelldir/ex2.info && /bin/rm /test/shelldir/ex2.info #crontab -e #0 9 * * 1-5 /bin /sh /test/ex2.sh
- 文件頭必須要有
- 變量
- 變量一般使用大寫字母定義
- 使用變量時要加前綴
$
- 給變量賦值時
=
號倆邊應該沒有空格 - 可以將命令的執行結果賦值給變量,但是要使用命令替換符號
- 單引號將內容原封不動輸出
- 雙引號會將變量值輸出
- 使用set命令查看所有的變量
- 使用unset命令刪除指定的變量
#!/bin/sh # 將命令的執行結果賦值給變量,但是要使用命令替換符號 DATE=`/bin/date +%Y%m%d` echo "TODAY IS $DATE" # 特殊的位置占位變量 $1,$2,$3分別是shell腳本執行時所傳遞的參數 # 每個shell最多的參數為9個,位置占位符最大為$9 /bin/ls -l $1 /bin/ls -l $2 /bin/ls -l $3
- 特殊變量
#!/bin/sh DATE=`/bin/date +%F` echo "today is $DATE" # 這個程序的參數個數 echo '$# :' $# # 執行上個后臺命令的pid echo '$! :' $! # 這個程序的所有參數 echo '$* :' $* # 顯示執行上一個命令的返回值 echo '$? :' $? # 這個程序的pid echo '$$ :' $$ # $(0-9)顯示占位變量 echo '$0 :' $0
- 鍵盤錄入
- 直接執行以下shell文件代碼,輸入三個參數,輸入回車
- sh -x *.sh可以跟蹤執行代碼
#!/bin/sh read f s t echo "the first is $f" echo "the second is $s" echo "the third is $t"
- shell運算
- expr命令,對整數進行運算
- expr的運算必須用空格間隔開
- * 表示轉義字符
- 先乘除后加減,如果要調整優先級,則要加命令替換符
-
也可以對變量進行運算操作
變量運算
- 測試語句
-
配合控制語句使用,不應單獨使用
測試語句
-
- if 語句
#!/bin/sh
# if test $1 then ... else ... fi
# if test -d $1 測試語句可以簡寫為 if [ -d $1 ] , 注意各個部分要有空格
if [ -d $1 ]
then
echo "this is a directory!"
else
echo "this is not a directory!"
fi
- elif 語句、
#!/bin/sh
# if test then ... elif test then ... else ... fi
if [ -d $1 ]
then
echo "is a directory!"
elif [ -f $1 ]
then
echo "is a file!"
else
echo "error!"
fi
- 邏輯與和邏輯或
#!/bin/sh
# -a 邏輯與(and) -o 邏輯或(or)
if [ $1 -eq $2 -a $1 = 1 ]
then
echo "param1 == param2 and param1 = 1"
elif [ $1 -ne $2 -o $1 = 2 ]
then
echo "param1 != param2 or param1 = 2"
else
echo "others"
fi
- for循環
#!/bin/sh
# for var in [名字表] do ... done
for var in 1 2 3 4 5 6 7 8 9 10
do
echo "number is $var"
done
- select 語句
#!/bin/sh
# select var in [params] do ... done
select var in "java" "c++" "php" "linux" "python" "ruby" "c#"
do
break
done
echo "you selected $var"
- case 語句
#!/bin/sh
read op
case $op in
a)
echo "you selected a";;
b)
echo "you selected b";;
c)
echo "you selected c";;
*)
echo "error"
esac
- while 循環語句
#!/bin/sh
#while test do ... done
num=1
sum=0
while [ $num -le 100 ]
do
sum=`expr $sum + $num`
num=`expr $num + 1`
done
#sleep 5
echo $sum
- continue和break語句
#!/bin/sh
i=0
while [ $i -le 100 ]
do
i=`expr $i + 1`
if [ $i -eq 5 -o $i -eq 10 ]
then continue;
else
echo "this number is $i"
fi
if [ $i -eq 15 ]
then break;
fi
done