shell 指令碼總結(常用指令碼)
阿新 • • 發佈:2020-10-15
常用shell指令碼總結
一、計算100以內奇偶數的和的幾種方法
1)、方法一 {1..100..2}
[[email protected] scirtp]# cat 6.sh #!/bin/sh evensum=0 for i in {1..100..2} do evensum=$[$evensum+$i] done echo "1+3+5+...=$evensum" oddsum=0 for I in {2..100..2} do oddsum=$[$oddsum+$I] done echo "2+4+6+..=:$oddsum." [[email protected] scirtp]# sh 6.sh 1+3+5+...=2500 2+4+6+..=:2550.
2)、方法二 `seq 1 2 100`
[[email protected] scirtp]# cat 6.sh #!/bin/sh evensum=0 for i in `seq 1 2 100` do evensum=$[$evensum+$i] done echo "1+3+5+...=$evensum" oddsum=0 for I in {2..100..2} do oddsum=$[$oddsum+$I] done echo "2+4+6+..=:$oddsum." [[email protected] scirtp]# sh 6.sh 1+3+5+...=2500 2+4+6+..=:2550. [[email protected] scirtp]#
3)、方法三 使用單個for迴圈
[[email protected] scirtp]# cat 5.sh #!/bin/sh oddsum=0 evensum=0 for i in {1..100} do if [ $[$i%2] -eq 0 ] then oddsum=$[$oddsum+$i] else evensum=$[$evensum+$i] fi done echo "2+4+6+..=$oddsum" echo "1+3+5+..=$evensum" [[email protected] scirtp]# sh 5.sh 2+4+6+..=2550 1+3+5+..=2500 [[email protected] scirtp]#
二、批量建立使用者
1、新增10個使用者user1, user2, ..., user10;並設定密碼,但要先判斷使用者是否存在,不存在而後再新增;
2、新增完成後,顯示一共添加了幾個使用者;當然,不能包括因為事先存在而沒有新增的;
3、最後顯示當前系統上共有多少個使用者
三、位置變數的應用($!,[email protected],$2....)
1)、使用位置變數($1),檢視輸入的使用者是否是計算機已有的使用者,如果是則比較其uid和gid是否相同。
[[email protected] scirtp]# cat 4.sh #!/bin/sh if id $1 &> /dev/null then echo "$1 exists" if [ `id -u $1` -eq `id -g $1` ] then echo "$1 uid 等於gid" else echo "$1 uid 不等於gid" fi else echo "$1 no exists" fi [[email protected] scirtp]# sh 4.sh root root exists root uid 等於gid [[email protected] scirtp]# sh 4.sh roott roott no exists [[email protected] scirtp]# sh 4.sh uucp uucp exists uucp uid 不等於gid
2)、通過引數傳遞一系列使用者名稱(a,b,c,d) 給指令碼,讓指令碼新增這些使用者;但要先判斷使用者是否存在,不存在而後再新增;新增完成後,顯示一共添加了幾個使用者;當然,不能包括因為事先存在而沒有新增的;
使用[email protected]位置變數
[[email protected] scirtp]# cat 7.sh #!/bin/bash # Count=0 for UserName in [email protected]; do if id $UserName &> /dev/null; then echo "$UserName exists." else useradd $UserName echo "Add $UserName successfully." Count=$[$Count+1] fi done echo "Add $Count new users." [[email protected] scirtp]# sh 7.sh a b c d Add a successfully. Add b successfully. Add c successfully. Add d successfully. Add 4 new users. [[email protected] scirtp]# tail -4 /etc/passwd a:x:4039:4039::/home/a:/bin/bash b:x:4040:4040::/home/b:/bin/bash c:x:4041:4041::/home/c:/bin/bash d:x:4042:4042::/home/d:/bin/bash [[email protected] scirtp]#si
四、shell中的字串比較
通過位置變數判斷一個使用者是否是bash使用者
改進之後
後續。。。。。。
在使用for迴圈在遇到的疑惑,曾經以為for迴圈定義的變數在for迴圈中一定要呼叫,這樣說可能不太理解,我也有點暈了,還是舉例吧
沒有使用變數,只是迴圈了5次
補充
將某個資料夾下所有的檔名字裡的大寫字母改成小寫字母
for file in `ls | grep '[A-Z]'` do str=`echo $file|tr 'A-Z' 'a-z'` mv $file $str done 1)ls | grep '[A-Z]' :ls 出所有含有大寫字母的檔案 2)for file in `command` :for 迴圈 3)echo AVdxFV | tr 'A-Z' 'a-z' : 把'AVdxFV' 中所有的大寫換成小寫字母; tr :translate的意思,具體看help
小編shell指令碼能力有限,不足之處還望各位博友多提寶貴意見,繼續改進,希望我們共同進步。。
轉載於:https://blog.51cto.com/xiaodong88/1252891