Shell腳本:
1、#! 指定腳本執行的shell
2、# 注釋
3、命令或語法結構
echo "輸入內容"
echo 輸出空行
執行:
1、shell 腳本
sh example
2、給shell腳本執行權限
chmod u+x example
案例:example sysinfo.sh
3abc x 不能以數字開頭
abc3
ABC3
環境變量-大寫
命令執行結果賦值變量使用 命令替換符 ``
PATH=$PATH:/root/shell.example
ls -l /etc/inittab /etc/fstab /etc/services
$0 $1 $2 $3
$0-$9
$* /etc/inittab /etc/fstab /etc/services
$# 3
$$ PID
$? 命令返回值 0 非0
案例:special.var
read 案例:read
expr 運算符前后要空格,乘號*要加轉義符
案例:expr
test
1、字符串測試 是否相等、是否為空
2、整數測試 相等、大于、小于
3、文件測試 文件類型、文件權限、文件存在、文件大小
單支循環:if/then
if 測試條件
then
執行操作
fi
APACHE=`/usr/bin/pgrep httpd`
if [ "$APACHE" = "" ]
then
/etc/rc.d/init.d/httpd start
fi
sh -x 腳本 在執行時顯示執行過程 +或++ 注釋
*/2 12-14 * 3-6,9-12 1-5 /root/shell-example/apache.test
雙支循環:if/else
if 測試語句
then
真: 操作
else
假: 操作
fi
案例:test.apache autobak.sh
tar -cf 新文件名 目錄
多支循環: if/elif
案例: if_else 判斷文件類型
條件連接 -o 邏輯或or -a 邏輯與and
exit退出語句
if [ "$#" != 2 ]
then
echo " MUST two parm!"
fi
echo "this is a test"
echo $1 $2
sh exit first
條件為真退出 exit 0 條件為假退出 exit 1 非0
添加exit語句 sh exit first
for循環
案例:for 自動將用戶踢出系統 killuser.sh
awk -F域分隔符 '命令' 默認分隔符就是空格
ps -le | grep httpd | awk '{print $4}'
awk -F: '$3==0 {print $1}' /etc/passwd
統計系統用戶數
awk -F: '$3>=500 {print $1}' /etc/passwd | grep -v nfsnobody | wc -l
awk -F: 'length($2)==0 {print $1}' /etc/shadow
case 案例:case /etc/rc.d/init.d/httpd
while 條件為真一直循環 案例:while useradd.sh
until 條件為假一直循環
echo 密碼 | passwd --stdin 用戶名
while計數循環
Windows寫腳本會有不可識別控制符要處理
dos2unix 腳本
新聞熱點
疑難解答