一、編寫一個腳本使我們在寫一個腳本時自動生成”#!/bin/bash”這一行和注釋信息。
原文代碼為:
1
2
3
4
5
6
7
8
9
10
|
#!/bin/bash
if ! grep "^#!" $1 &>/dev/null; then
cat >> $1 << EOF
#!/bin/bash
# Author:
#Date & Time: `date +"%F %T"`
#Description:
EOF
fi
vim +5 $1
|
初學者看到這代碼,可能不太會用,其實很簡單,看到有$1,就表示需要帶參數來執行,所以,這個腳本的執行方法是:
①、將以上代碼保存為shell腳本,比如test,
②、使用chmod加上執行權限,chmod +x test
③、執行 ./test newfile 即可看到效果。
Ps:當然也可以不要第②步,直接使用 sh test newfile 即可。
執行效果如下:
這個腳本對於經常寫shell的童鞋就很有用,但是忘記帶參數執行就會卡住不動,而且不帶路徑的話就直接在當前目錄下生成新文件,會很亂。所以張戈就將其改進一下,變得更加易用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
#!/bin/bash
if [[ -z "$1" ]];then
newfile=~/newscript_`date +%m%d_%S`
else
newfile=$1
fi
if ! grep "^#!" $newfile &>/dev/null; then
cat >> $newfile << EOF
#!/bin/bash
# Author: Inert Your Name here.
#Date & Time: `date +"%F %T"`
#Description: Please Edit here.
EOF
fi
vim +5 $newfile
|
改進說明:如果未帶參數執行,將在家目錄下生成帶時間戳的新文件,避免重復及亂的問題。可將這個腳本改名后直接丟到path路徑中,比如/bin/addjb 那么你的系統就多了一個命令 addjb了,是不是很有趣呢!
時間有限,以下腳本暫時就不做測試、解釋或改進了,請先自行測試吧!有空再來更新。
二、任意三個整數,判斷最大數。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
#!/bin/bash
echo "please enter three number:"
read -p "the first number is :" n1
read -p "the second number is:" n2
read -p "the third number is:" n3
let MAX=$n1
if [ $n2 -ge $n1 ]; then
MAX=$n2
fi
if [ $n3 -ge $MAX ]; then
MAX=$n3
fi
echo "the max number is $MAX."
|
執行效果:
注:非常簡單的邏輯判斷腳本,有興趣的可以改進下,練練手。
三、求100以內偶數的和。
方法①:
1
2
3
4
5
6
|
#!/bin/bash
sum=0
for I in {1..50}; do
sum=$(($sum+2*$I))
done
echo "the sum is $sum"
|
方法②:
1
2
3
4
5
6
7
8
|
#!/bin/bash
let SUM=0
for I in $(seq 1 100); do
if [ $[$I%2] == 0 ]; then
let SUM+=$I
fi
done
echo "the sum is $SUM."
|
四、利用for語句ping C類網、ping B類網。
①、ping C類網:
1
2
3
4
5
6
7
8
9
|
#!/bin/bash
read -p "C NETWORK:" MYNET
PINGNET=`echo $MYNET | sed 's/\([0-9.]*\)\ .[0-9]*/\1/g'`
let I=1
while [ $I -le 254 ];do
ping –c1 –W1 $PINGNET.$I &>/dev/null
[ $? -eq 0 ] && echo "$PINGNET.$I online." || echo "$PINGNET.$I offline."
let I++
done
|
②、ping B類網:
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash
read -p "B network:" MYNET
PINGNET=`echo $MYNET | sed 's/\([0-9]\{1,3\}\.[0-9]\{1,3\}\)\..*/\1/g'`
for P in {0..255}; do
for I in {1..255}; do
if ping -c1 -W2 $PINGNET.$P.$I &>/dev/null; then
echo "$PINGNET.$P.$I is online."
else
echo "$PINGNET.$P.$I is offline."
fi
done
done
|
五、提示輸入一個用戶名,判斷用戶是否存在,如果存在,顯示一下用戶默認的shell。
1
2
3
4
5
6
7
8
9
|
#!bin/bash
read –p "please input a username:" USER
if cut –d:-f1 /etc/passwd | grep "^$USER$" &> /dev/null ;then
MYBASH=`grep "^$USER:" /etc/passwd | cut –d : -f7`
echo "${USER}'s shell is $MYBASH"
else
echo "$USER not exists."
exit 4
fi
|
六、監控系統登錄人數,超過四個,顯示已經達到四個,5S檢查一下,並退出腳本(exit)
1
2
3
4
5
6
7
8
9
|
#! /bin/bash
read –p "A user:" MYUSER
cut –d : -f1 /etc/passwd | grep "^$MYUSER" &> /dev/null || exit 6
let COUNT=`who | grep "^$MYUSER" | wc –l`
until [ $COUNT –ge 4 ]; do
sleep 5
let COUNT=`who | grep “^$MYUSER” | wc -l`
done
echo "$MYUSER loged 4 times."
|