linux shell腳本基礎(chǔ)知識學習
Shell腳本:
1、#! 指定腳本執(zhí)行的shell
2、# 注釋
3、命令或語法結(jié)構(gòu)
echo "輸入內(nèi)容"
echo 輸出空行
執(zhí)行:
1、shell 腳本
sh example
2、給shell腳本執(zhí)行權(quán)限
chmod u+x example
案例:example sysinfo.sh
3abc x 不能以數(shù)字開頭
abc3
ABC3
環(huán)境變量-大寫
命令執(zhí)行結(jié)果賦值變量使用 命令替換符 ``
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 運算符前后要空格,乘號*要加轉(zhuǎn)義符
案例:expr
test
1、字符串測試 是否相等、是否為空
2、整數(shù)測試 相等、大于、小于
3、文件測試 文件類型、文件權(quán)限、文件存在、文件大小
單支循環(huán):if/then
if 測試條件
then
執(zhí)行操作
fi
APACHE=`/usr/bin/pgrep httpd`
if [ "$APACHE" = "" ]
then
/etc/rc.d/init.d/httpd start
fi
sh -x 腳本 在執(zhí)行時顯示執(zhí)行過程 +或++ 注釋
*/2 12-14 * 3-6,9-12 1-5 /root/shell-example/apache.test
雙支循環(huán):if/else
if 測試語句
then
真: 操作
else
假: 操作
fi
案例:test.apache autobak.sh
tar -cf 新文件名 目錄
多支循環(huán): 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循環(huán)
案例:for 自動將用戶踢出系統(tǒng) killuser.sh
awk -F域分隔符 '命令' 默認分隔符就是空格
ps -le | grep httpd | awk '{print $4}'
awk -F: '$3==0 {print $1}' /etc/passwd
統(tǒng)計系統(tǒng)用戶數(shù)
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 條件為真一直循環(huán) 案例:while useradd.sh
until 條件為假一直循環(huán)
echo 密碼 | passwd --stdin 用戶名
while計數(shù)循環(huán)
Windows寫腳本會有不可識別控制符要處理
dos2unix 腳本
相關(guān)文章
一文學會使用Linux內(nèi)核模塊&proc實例統(tǒng)計所有進程信息
這篇文章主要介紹了使用Linux內(nèi)核模塊&proc實例統(tǒng)計所有進程信息詳解,2023-05-05編寫shell腳本將VPS上的數(shù)據(jù)備份到Dropbox網(wǎng)盤的方法
這篇文章主要介紹了編寫shell腳本將VPS上的數(shù)據(jù)備份到Dropbox網(wǎng)盤的方法,注意Dropbox在國內(nèi)訪問的網(wǎng)絡(luò)相關(guān)問題,需要的朋友可以參考下2015-07-07