變量腳本node
一、編寫腳本/root/bin/systeminfo.sh,顯示當前主機系統信息,包括主機名,IPv4地址,操做系統版本,內核版本,CPU型號,內存大小,硬盤大小linux
server_ip=ifconfig|grep'inet\b'|grep -v '127.0.0.1'|tr-s ' '|cut -d' ' -f3
CPUmod=lscpu|grep -i "model name:"
Meminfo=free -h|sed -n '2p'|tr -s ' '|cut -d' ' -f2
DISKinfo=fdisk -l |sed -n '2p'|sed -r 's/.*[[:space:]][0-9].*GB).*/\1/g
git
echo 'hostname:' $(hostname)
echo 'hostIP:' ${server_ip}
echo 'OS version:' $(cat /etc/redhat-release)
echo 'Kernel version:' $(uname -r)
echo 'CPU:' $CPUmod
echo 'Memory:' $Meminfo
echo 'Harddisk:' $DISKinfo算法
二、編寫腳本/root/bin/backup.sh,可實現每日將/etc/目錄備份到/root/etcYYYY-mm-dd中數組
backupdir="/root/etc$(date +%F)"
cp -a /etc $backupdir
echo "backup $backupdir finished."bash
三、編寫腳本/root/bin/disk.sh,顯示當前硬盤分區中空間利用率最大的值網絡
maxused=df -h|grep '/dev/sd' |tr -s ' '|sort -nr -t' ' -k5 |head -l |cut -d' ' -f5
echo'硬盤分區利用率最大值爲:'$maxusedapp
四、編寫腳本/root/bin/links.sh,顯示正鏈接本主機的每一個遠程主機的IPv4地址和鏈接數,並按鏈接數從大到小排序dom
netstat -nt |tr -s ' '|cut -d' ' -f5|tr -cs'0-9.' '\n'|egrep'([0-9]+.){3}[0-9]+'|sort |uniq -c|sort -nr|tr -s ' 'socket
'\t'
一、編寫腳本/root/bin/sumid.sh,計算/etc/passwd文件中的第10個用戶和第20用戶的ID之和
dir=/etc/passwd
n=10
m=20
id_10=cat $dir|head -$n|tail -1|cut -d: -f3
id_20=cat $dir|head -$m|tail -1|cut -d: -f3
num=$[id_10+id_20]
====================================================
UID1=sed -n '10p'/etc/passwd |cut -d: -f3
UID2=sed -n '20p'/etc/passwd |cut -d: -f3
let Sumid=$UID1+$UID2
二、編寫腳本/root/bin/sumspace.sh,傳遞兩個文件路徑做爲參數給腳本,計算這兩個文件中全部空白行之和
File1=grep'^$' $1|wc -l
File2=grep'^$' $2|wc -l
let Sumspace=$File1+$File2
echo "the sum of $1 + $2 spacelines is $Sumspace"
unset File1
unset File2
unset Sumspace
三、編寫腳本/root/bin/sumfile.sh,統計/etc, /var, /usr目錄中共有多少個一級子目錄和文件
File1=ls -A /etc |wc -l
File2=ls -A /var |wc -l
File3=ls -A /usr |wc -l
let Sumfile=$File1+$File2+$File3
echo "the sum is $Sumfile"
unset File1
unset File2
unset File3
unset Sumfile
文本測試腳本
一、編寫腳本/root/bin/argsnum.sh,接受一個文件路徑做爲參數;若是參數個數小於1,則提示用戶「至少應該給一個參數」,並當即退出;若是參數個數不小於1,則顯示第一個參數所指向的文件中的空白行數
[[$# -lt 1]] && echo "at least a parameter" ||(grep '^$' $1 |wc -l)
二、編寫腳本/root/bin/hostping.sh,接受一個主機的IPv4地址作爲參數,測試是否可連通。若是能ping通,則提示用戶「該IP地址可訪問」;若是不可ping通,則提示用戶「該IP地址不可訪問」
ping -c1 -w1 $1 &>/dev/null && [[$? -eq 0]] && echo "該IP地址能夠訪問"||echo "該IP地址不能夠訪問"
三、編寫腳本/root/bin/checkdisk.sh,檢查磁盤分區空間和inode使用率,若是超過80%,就發廣播警告空間將滿
disk= df |tr -s " "|cut -d" " -f5|cut -d% -f1|sort -n|tail -1
inode=df -i|tr -s " "|cut -d" " -f5|cut -d% -f1|sort -n|tail -1
[[ $disk -ge 80 ]] && "echo "80%" | mail -s diskover80% root"
[[ $inode -ge 80 ]] && "echo "80%" | mail -s inodeover80% root"
判斷主機名是否爲空, 或等於指定主機名, 若是是, 則更名爲
[ -z 「$HOSTNAME」 -o $HOSTNAME ==\"localhost.localdomain" ] && hostname www.magedu.com
判斷文件是否普通文件和有執行權限, 若是是, 則輸出文件內容
[ -f /bin/cat -a -x /bin/cat ] && cat /etc/fstab
一、編寫腳本/bin/per.sh,判斷當前用戶對指定的參數文件,是否不可讀而且不可寫
[! -r $1 -a ! -w $1 ] && echo "can't r can't w" || echo " can r can w"
二、編寫腳本/root/bin/excute.sh ,判斷參數文件是否爲sh後綴的普通文件,若是是,添加全部人可執行權限,不然提示用戶非腳本文件
[ -f $1 -a ${$1##*.} == "sh" ]&& chmod +x $1 && echo "have right"||echo "error"
三、編寫腳本/root/bin/nologin.sh和login.sh,實現禁止和容許普通用戶登陸系統
[ -e $1 ] && echo "you can login" || (rm -rf /home/whoami
; echo "you can login")
[ -e $1 ] && (rm -rf /home/whoami
; echo "you can not login")||echo "you can login"
===============================================================
[ -f /etc/nologin ] && (echo "普通用戶已不能登陸")|| (touch /etc/nologin)
寫一個腳本/root/bin/hostping.sh,接受一個主機的IPv4地址作爲參數,先判斷是否合格IP,否,提示IP格式不合法並退出,是,測試是否可連通。若是能ping通,則提示用戶「該IP地址可訪問」;若是不可ping通,則提示用戶「該IP地址不可訪問」
[[$# -lt 1]] && echo "須要一個IP地址做爲參數" $$ exit
[["$1"=~(([0-9]|[0-9][1-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[0-9][1-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$]]
[ $? -ne 0 ] && echo "IP地址不合法" && exit
ping -c1 -W1 $1 > /dev/null && echo "IP能夠被正常訪問" || echo "IP不能被正常訪問"
計算1+2+3+...+100的值
echo seq -s + 1 100 |bc
==========================
echo $[seq -s + 1 100
]
計算從腳本第一參數A開始,到第二個參數B的全部數字的總和,判斷B是否大於A,否提示錯誤並退出,是則計算之
sumNtoN1.sh
[[ $# -lt 2 ]] && echo "至少須要兩個不一樣的整數做爲參數,第一個參數須要小於第二個參數" && exit
[[ $1 =~ \b[[:digit:]]+\b ]]
[ $? -ne 0 ] && echo "第一個參數必須爲整數" && exit
[[ $2 =~ ^[[:digit:]]+$ ]]
[ $? -ne 0 ] && echo "第二個參數必須爲整數" && exit
[[ $1 -eq $2 ]] && echo "兩個整數不能相同" && exit
[[ $1 -ge $2 ]] && echo "第一個參數須要小於第二個參數" && exit
echo -n "$1到$2之間全部整數的和爲"
echo seq $1 $2 | tr '\n' '+' | sed -r 's@\+$@@g'
| bc
============================
echo seq -s + $1 $2 |bc
腳本判斷年齡
checkage.sh
read -p "How old are you?" age
if [ $age -ge 0 -a $age -le 18 ];then
echo "hello,baby"
elif [ $age -gt 18 -a $age -le 60 ];then
echo "work hard"
elif [ $age -gt 60 -a $age -le 150 ];then
echo "happy day"
else
echo "welcome to the earth"
fi
根據命令的退出狀態來執行命令
if ping -c1 -W2 station1 &> /dev/null; then
echo 'Station1 is UP'
elif grep "station1" ~/maintenance.txt &>/dev/null
then
echo'Station1isundergoingmaintenance'
else
echo'Station1isunexpectedlyDOWN!'
exit1
fi
條件腳本
一、編寫腳本/root/bin/createuser.sh,實現以下功能:使用一個用戶名作爲參數,若是指定參數的用戶存在,就顯示其存在,不然添加之;顯示添加的用戶的id號等信息
useradd $1 &> /dev/null
if [ $? -eq 0 ]
then
echo "user $1 add"
id $1
else
echo "user exist already or no argument "
fi
二、編寫腳本/root/bin/yesorno.sh,提示用戶輸入yes或no,並判斷用戶輸入的是yes仍是no,或是其它信息
yesorno2.sh
echo -n "Enter you choice yes|no:"
read Choice
Choice1=echo $Choice | tr '[a-z]' '[A-Z]'
case $Choice1 in
Y|YES)
echo "you select yes."
;;
N|NO)
echo "you select no."
;;
*)
echo "you select others."
;;
esac
#
unset Choice
unset Choice1
========================================
yesorno3.sh
read -p "please enter yes/no: " yesorno
case $yesorno in
[yY][Ee][Ss]|[Yy])
echo "Yes"
;;
[Nn][Oo]|[Nn])
echo "No"
;;
*)
echo "Other char"
;;
esac
三、編寫腳本/root/bin/filetype.sh,判斷用戶輸入文件路徑,顯示其文件類型(普通,目錄,連接,其它文件類型)
read -p "please enter file: " filename
if [ -L $filename ];then
echo "$filename is Symbol file."
elif [ -c $filename ];then
echo "$filename is char file."
elif [ -d $filename ];then
echo "$filename is dir file."
elif [ -b $filename ];then
echo "$filename is block file."
elif [ -f $filename ];then
echo "$filename is common file."
elif [ -p $filename ];then
echo "$filename is pipe file."
elif [ -S $filename ];then
echo "$filename is socket file."
else
echo "please enter a Correct file"
fi
===============================================
if [[ $# -lt 1 ]]
then
echo -e "Error: No argument.\n\tUsage: $0 FILENAME"
exit 1
else
if [[ -e $1 ]]
then
FileType=ls -ld $1 | cut -c1
case $FileType in
l)
echo "$1 is a link file"
;;
d)
echo "$1 is a diretory"
;;
-)
echo "$1 is a common file"
;;
*)
echo "$1 is other file"
;;
esac
else
echo "$1: no such file or diretory."
fi
fi
unset FileType
四、編寫腳本/root/bin/checkint.sh,判斷用戶輸入的參數是否爲正整數
read -p "please input a number: " number
[ -z "$number" ] && echo "you must input a number " && exit
if let var=$number &> /dev/null ; then
if [ "$?" -eq 0 ]; then
if [ "$number" -lt 0 ]; then
echo "$number is 負整數"
elif [ $number -eq 0 ]
echo " $number is 零"
else
echo "$number is 正整數"
fi
fi
else
echo "$number 不是一個整數"
fi
=================================================
read -p "請入一個數字: " num
[ -z "$num" ]&&echo "請輸入一個數字"&&exit 1
NUM=$(echo $num |grep -Eo "-?[[:digit:]]+")
if [ "$NUM" == "$num" ];then
if [ "$NUM" -lt "0" ];then
echo "您輸入的是一個負整數"
elif [ "$NUM" -eq "0" ];then
echo "您輸入的是一個0"
else
echo "您輸入的是一個正整數"
fi
else
echo "您輸入的不是一個整數 請從新運行腳本"
fi
循環腳本
for腳本
for2.sh
#!/bin/bash
for i in {1.3}
do
echo $i
for i in {1..10}
do
echo -e "$i\c"
done
echo $i
done
編寫腳本刪除大於1000的屬組
delUserGt1000.sh
#!/bin/bash
#
for groupentry in getent group | cut -d: -f1,3
;do
groupna=echo $groupentry | cut -d: -f1
groupidnum=echo $groupentry | cut -d: -f2
#echo -e "$groupna $groupidnum \n"
[[ $groupidnum -gt 1000 ]] && groupdel "$groupna"
done
==============================
groupdel.sh
GID=getent group| cut -d: -f3
for i in $GID
do
if [ $GID -gt 1000];then
GroupName=getent group|grep "$GID"|cut -d: -f1
groupdel $GroupName &>/dev/null
else
echo "the group is system group"
fi
done
一、判斷/var/目錄下全部文件的類型
模塊化調用
for filename in /var/*; do echo $filename |filetype.sh; done
==============================================================
forfiletype.sh
if [[ $# -lt 1 ]]
then
echo -e "Error: No argument.\nUsage: $0 DIR"
exit 1
fi
#=============== plan 1 =================
if [[ ! -d $1 ]]
then
echo "Error: $1 is not a diretory or No such file."
exit 2
fi
DirName=echo $1 | sed -r 's@(.*)/$@\1@'
for i in ls -A $1
do
FileType=ls -dl $DirName/$i | cut -c1
case $FileType in
d)
echo "$DirName/$i is a diretory."
;;
-)
echo "$DirName/$i is a common file."
;;
l)
echo "$DirName/$i is a link file."
;;
b)
echo "$DirName/$i is a block file."
;;
c)
echo "$DirName/$i is a character file."
;;
p)
echo "$DirName/$i is a pipe file."
;;
s)
echo "$DirName/$i is a socket file."
;;
*)
echo "$DirName/$i is unkwon file"
;;
esac
done
#================== plan 2 ==============
cd $1 &> /dev/null
if [[ $? = 0 ]]
then
for i in ls -A $1
do
FileType=ls -dl $DirName/$i | cut -c1
case $FileType in
d)
echo "$i is a diretory."
;;
-)
echo "$i is a common file."
;;
l)
echo "$i is a link file."
;;
b)
echo "$i is a block file."
;;
c)
echo "$i is a character file."
;;
p)
echo "$i is a pipe file."
;;
s)
echo "$i is a socket file."
;;
*)
echo "$i is other file"
;;
esac
done
else
echo "$1 is not a diretory"
exit 2
fi
unset DirName
unset FileType
二、添加10個用戶user1-user10,密碼同用戶名
foruserAD
if [[ $# -lt 1 ]]
then
echo -e "Error: No option \n\t-d\tdelete user1-user10\n\t-a\tadd user1-user10 "
exit 1
fi
for i in $(seq 10);do
case $1 in
-d|--del)
if id user$i &> /dev/null;then
userdel -r user$i
echo "user$i: Delete complete!"
else
echo "user$i: No such user!"
fi
;;
-a|--add)
if id user$i &> /dev/null;then
echo "user$i"| passwd --stdin "user$i" &> /dev/null
echo -e "user$i: Already existed!\nAnd authentication tokens updated successful!"
else
useradd user$i &> /dev/null
echo "user$i"| passwd --stdin "user$i" &> /dev/null
echo " user$i: Add complete!"
fi
;;
*)
echo "Error:"
echo -e "$0 : Unknow option!\nplease use '-a''--add' to add user or '-d''--dell'to delect user"
exit 1
;;
esac
done
三、/etc/rc.d/rc3.d目錄下分別有多個以K開頭和以S開頭的文件;分別讀取每一個文件,以K開頭的文件輸出爲文件加stop,以S開頭的文件輸出爲文件名加start;「K34filename stop」「S66filename start」
forrc3.sh
for i in ls /etc/rc.d/rc3.d
do
FileC1=echo $i | cut -c1
case $FileC1 in
K)
echo -e "$i\tstop"
;;
S)
echo -e "$i\tstart"
;;
*)
echo "unkown file"
;;
esac
done
四、編寫腳本,提示輸入正整數n的值,計算1+2+3+…n的總和
and.sh
#!/bin/bash
read -p 'please input the number' n
num=echo $n|grep "^[[:digit:]]\+$"
if echo $n|grep -q "^[[:digit:]]+$" ;then
if [ $num -eq 0 ];then
echo "the number is 0"
exit
fi
else
echo "the number is negtive"
exit
fi
string=0
for i in seq $n
;do
sum=$[$sum+$i]
string=$string+$i
done
echo "$string=$sum"
================================
read -p "please input n:" n
sum=0;for i in {1..n};
do
sum=$(($sum+1));
done;
echo $sum
五、編寫腳本,提示請輸入網絡地址,如192.168.0.0,判斷輸入的網段中主機在線狀態
fortestIP.sh
echo -n "Enter IP:"
read IP
#get IP segment
Segment=echo $IP | cut -d. -f1-3
.
#
if echo $IP | egrep '\<([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).){2}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\>' &>/dev/null
then
#test host
for i in seq 240 255
do
if ping -c 1 -W 1 $Segment$i &> /dev/null
then
echo -e "$Segment$i\tonline"
else
echo -e "$Segment$i\toffline"
fi
done
else
echo "$IP is invalid"
fi
六、打印九九乘法表
for99tables.sh
for i in seq 9
do
for j in seq 1 $i
do
echo -ne "$i$j=$(($i$j))\t"
done
echo
done
echo "==================== plan 2 ===================="
for (( i=1 ; i<=9 ; i++ ))
do
for (( j=1 ; j<=i ; j++ ))
do
echo -ne "$i$j=$(($i$j))\t"
done
echo
done
unset i
unset j
while腳本
i=1;while [$i -le 9 ]; do echo $i; let i++;done
一、編寫腳本,求100之內全部正整數之和
i=1
sum=0
while [ $i -le 100 ] ;do
sum=$(expr $sum + $i )
let i++
done
echo $sum
=======================
sum=0
i=1
while(( i <= 100 ))
do
let "sum+=i"
let "i += 1"
done
echo "sum=$sum"
二、編寫腳本,經過ping命令探測172.16.250.1-254範圍內的全部主機的在線狀態,統計在線主機和離線主機各多少。
whilenetstatus.sh
read -p "Please Input network:" a
i=0
j=0
k=0
while [ $i -le 255 ];do
ping -c1 -W1 $a$i &> /dev/null
if [ $? -eq 0 ];then
echo "$a$i is active"
let j++
else
echo "$a$i is inactive"
let k++
fi
let i++
done
echo "the sum number of active users is $j"
echo "the sum number of inactive users is $k"
三、編寫腳本,打印九九乘法表
while3.sh
i=1
while [ $i -le 9 ];do
j=1
while [ $j -le $i ];do
mul=$[$i$j]
echo -ne "$i$j=$mul\t"
j=$[$j+1]
done
echo
i=$[$i+1]
done
==========================================
i=1
j=1
while [ "$i" -ne 10 ]
do
while [ "$j" -ne 10 ]
do
((product=$i$j))
echo -ne $i\$j=$product"\t"
((j++))
done
j=1
((i++))
echo
done
exit 0
四、編寫腳本,利用變量RANDOM生成10個隨機數字,輸出這個10數字,並顯示其中的最大者和最小者
random.sh
cat /dev/null > /root/random.txt
declare -i num=1
while [ $num -le 10 ];do
echo $RANDOM | tee -a /root/random.txt
let num++
done
echo "min: "
sort -n /root/random.txt | head -1
echo "max: "
sort -n /root/random.txt | tail -1
============================================
addr.sh
i=10
a=$RANDOM
max=$a
min=$a
while [ $i -ge 1 ]
do
[ $max -lt $a ] && max=$a
[ $min -gt $a ] && min=$a
echo "$a"
a=$RANDOM
let i--
done
echo "最大值$max"
echo "最小值$min"
============================================
declare -i MAX=0
declare -i MIN=0
for I in {1..10};do
MYRAND=$RANDOM
[ $I -eq 1 ] && MIN=$RANDOM
if [ $I -le 9 ];then
echo -n "$MYRAND,"
else
echo "$MYRAND"
fi
[ $MYRAND -gt $MAX ] && MAX=$MYRAND
[ $MYRAND -lt $MIN ] && MIN=$MYRAND
done
echo $MAX,$MIN
五、編寫腳本,實現打印國際象棋棋盤
xiangqi
i=1
while [ $i -le 8 ];do
j=1
while [ $j -le 8 ];do
sum=expr $i + $j
z=expr $sum % 2
[ $z -eq 0 ] && echo -ne "\033[41;1m \033[0m"||echo -ne "\033[43;1m \033[0m"
let j++
done
echo
let i++
done
===================================
while5
declare -i i=1
declare -i j=1
while [ $i -lt 9 ];do
if [ $[$i%2] -eq 0 ] ;then
while [ $j -lt 9 ];do
if [ $[$j%2] -ne 0 ];then
echo -en "\e[43;37m \e[0m"
else
echo -en "\e[45;37m \e[0m"
fi
let j++
done
else
while [ $j -lt 9 ];do
if [ $[$j%2] -eq 0 ];then
echo -en "\e[43;37m \e[0m"
else
echo -en "\e[45;37m \e[0m"
fi
let j++
done
fi
declare -i j=1
let i++
echo ""
done
unset i;unset j
untill腳本
#!/bin/bash
i=1
until [ $i -ge 10 ]
do
echo $i
let i++
done
循環控制腳本
一、每隔3秒鐘到系統上獲取已經登陸的用戶的信息;若是發現用戶hacker登陸,則將登陸時間和主機記錄於日誌/var/log/login.log中,並提示該用戶退出系統。
untilremind.sh
until who |grep -q "^hacker\b" ;do
sleep 3
done
who | grep "^hacker"|tr -s ' '|cut -d' ' -f3,5 >> /var/log/login.log
echo "you should logout system" | mail hacker
echo "reminded and login record in /var/log/login.log"
二、隨機生成10之內的數字,實現猜字遊戲,提示比較大或小,相等則退出。
cai.sh
#!/bin/bash
suiji=$[$RANDOM%10+1]
read -p "我猜:" shuru
until [[ $suiji -eq $shuru ]]; do
[ $shuru -lt $suiji ] && echo "小了"
[ $shuru -gt $suiji ] && echo "大了"
read -p "我猜:" shuru
done
echo "猜中了,退出"
============================================
numberguess.sh
MAX=50
guess=1
let answer=($RANDOM % $MAX)
let answer+=1
ceiling=$MAX
floor=0
guesses=0
until [ "$guess" -eq "$answer" ]
do
echo "The magic number is between $floor and $ceiling."
echo -en "Make your guess:"
read guess
guesses=expr $guesses + 1
if [ "$guess" -lt "$answer" ];then
echo "$guess is too low"
if [ "$guess" -gt "$floor" ];then
floor=expr $guess + 1
fi
fi
if [ "$guess" -gt "$answer" ];then
echo "$guess is too hight"
if [ "$guess" -lt "$ceiling" ];then
ceiling=expr $guess - 1
fi
fi
done
echo "You got it in $guesses guesses!"
顯示三角形
*
#!/bin/bash
read -p "Please Input line number:" Line
for ((i=1; i<=Line; i++))
do
for ((j=$Line-$i; j>0; j--));
do
echo -n ' '
done
for ((h=1; h<=$((2*$i-1)); h++)) do echo -n '*' done echo
done
顯示倒三角
#!/bin/bash
read -p "Please Input line number:" Line
for ((i=0; i<$Line; i++))
do
for ((j=$i; j>0; j--))
do
echo -n " "
done
for ((h=$((2*($Line-$i)-1)); h>0; h--)) do echo -n "*" done echo
done
二、用until循環實現國際象棋棋盤
#!/bin/bash
i=1
until [ $i -gt 8 ];do
j=1
until [ $j -gt 8 ];do
sum=expr $i + $j
z=expr $sum % 2
[ $z -eq 0 ] && echo -ne "\033[41;1m \033[0m"||echo -ne "\033[43;1m \033[0m"
let j++
done
echo
let i++
done
while read line; do 循環體 done < FILE 依次讀取文件每行給變量
計算UID總和
sum=0; while read line; do sum=$[sum+echo $line|cut -d: -f3
]; done < /etc/passwd; echo $sum
掃描/etc/passwd文件每一行,如發現GECOS字段爲空,則填充用戶名和單位電話爲62985600,並提示該用戶的GECOS信息修改爲功。
while read line;do
GECOS=$(echo $line | cut -d: -f5)
if [[-z "$GECOS"]]; then
name=$(echo $line | cut -d: -f1)
chfn -f $name $name &>/dev/null chfn -p 62985600 $name &> /dev/null echo "$name GEGOS was modified" fi
done < /etc/passwd
select 菜單
select abc in aa bb cc; do echo "$abc"; done
select abc in aa bb cc
do
case $abc in
aa)
echo "11"
;;
bb)
echo "22"
;;
*)
echo "00"
break
;;
esac
done
select abc
do
case $abc in
aa)
echo "$REPLY"
;;
bb)
echo "$REPLY"
;;
*)
echo "$REPLY"
break
;;
esac
done
countinue腳本
for i in {1..3}
do
for j in {10..20}
do
[ $j -eq 15 ]&&continue
echo $j
done
done
for i in {1..3}
do
for j in {10..20}
do
[ $j -eq 15 ]&&continue 2
echo $j
done
done
for i in {1..3}
do
for j in {10..20}
do
[ $j -eq 15 ]&&break
echo $j
done
done
for i in {1..3}
do
for j in {10..20}
do
[ $j -eq 15 ]&&break 2
echo $j
done
done
函數
is_true() {
case "$1" in
[tT]|[yY]|[yY][eE][sS]|[tT][rR][uU][eE]
return 0
;;
esac
return 1
}
is_false() {
case "$1" in
[fF]|[nN]|[nN][oO]|[fF][aA][lL][sS][eE]
return 0
;;
esac
return 1
}
function fun1 () { echo "abcdefg"; }
alias fun1=ls
fun1
unalias fun1
fun1
unset fun1
fun1
alias fun1=ls
function fun1 () { echo "abcdefg"; }
fun1
unset fun1
fun1
unalias fun1
fun1
函數自調用次數極限
fun() { let i++ ;echo $i; fun; }
函數遞歸
階乘
#!/bin/bash
fact() {
if [ $1 eq 0 -o $1 -eq 1 ]; then
echo 1
else
echo $[$1*fact $[$1-1]
]
fi
}
fact $1
函數
一、 編寫服務腳本/root/bin/testsrv.sh,完成以下要求
(1) 腳本可接受參數:start, stop, restart, status
(2) 若是參數非此四者之一,提示使用格式後報錯退出
(3) 如是start:則建立/var/lock/subsys/SCRIPT_NAME, 並顯示「啓動成功」
考慮:若是事先已經啓動過一次,該如何處理?
(4) 如是stop:則刪除/var/lock/subsys/SCRIPT_NAME, 並顯示「中止完成」
考慮:若是事先已然中止過了,該如何處理?
(5) 如是restart,則先stop, 再start
考慮:若是原本沒有start,如何處理?
(6) 如是status, 則若是/var/lock/subsys/SCRIPT_NAME文件存在,則顯示「SCRIPT_NAMEis running...」
若是/var/lock/subsys/SCRIPT_NAME文件不存在,則顯示「SCRIPT_NAME is stopped...」
其中:SCRIPT_NAME爲當前腳本名
(7) 在全部模式下禁止啓動該服務,可用chkconfig和service命令管理
usagte(){
echo "Usage: $prog {start|stop|restart|status}"
}
if [ $# -lt 1 ]; then
usage
exit 1
fi
start(){
if [ -e $lockfile ]; then
echo "$prog is already running."
return 0
else
touch $lockfile
[ $? -eq 0 ] && echo "Starting $prog finished."
fi
}
stop(){
if [ -e $lockfile ]; then
rm -f $lockfile && echo "Stop $prog ok."
else
echo "$prog is stopped yet."
fi
}
status(){
if [ -e $lockfile ]; then
echo "$prog is running."
else
echo "$prog is stopped."
fi
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status
;;
*)
usage
esac
二、 編寫腳本/root/bin/copycmd.sh
(1) 提示用戶輸入一個可執行命令名稱;
(2) 獲取此命令所依賴到的全部庫文件列表
(3) 複製命令至某目標目錄(例如/mnt/sysroot)下的對應路徑下;
如:/bin/bash ==> /mnt/sysroot/bin/bash
/usr/bin/passwd==> /mnt/sysroot/usr/bin/passwd
(4) 複製此命令依賴到的全部庫文件至目標目錄下的對應路徑下:
如:/lib64/ld-linux-x86-64.so.2 ==> /mnt/sysroot/lib64/ld-linux-x86-64.so.2
(5) 每次複製完成一個命令後,不要退出,而是提示用戶鍵入新的要複製的命令,並重復完成上述功能;直到用戶輸入quit退出
#!/bin/bash
ch_root="/mnt/sysroot"
[ ! -d $ch_root ] && mkdir $ch_root
bincopy() {
if which $1 $>/dev/null; then
local cmd_path="which --skip-alias $1" local bin_dir="dirname $cmd_path" [ -d ${ch_root}${bin_dir} ] || mkdir -p ${ch_root}${bin_dir} [ -f ${ch_root}${cmd_path}] || cp $cmd_path ${ch_root}${bin_dir} return 0 else echo "Command not found." return 1 fi
}
libcopy() {
local lib_list=$(ldd which --skip-alias $1
| grep -Eo '/[^[:space:]]+')
for loop in $lib_list;do
local lib_dir=dirname $loop
[ -d $ {ch_root}${lib_dir} ] || mkdir -p ${ch_root}${lib_dir}
[ -f $ {ch_root}${loop} ] || cp $loop ${ch_root}${lib_dir}
done
}
read -p "Please input a command:" command
while [ "$command" != "quit" ]; do
if bincopy $command ; then
libcopy $command
fi
read -p "Please input a command or quit: "command
done
三、編寫函數實現兩個數字作爲參數,返回最大值
#!/bin/bash
source funs.sh
funs.sh
#!/bin/bash
echo "please enter two number"
read a
read b
if test $a -eq $b
then echo "two same: "$a
elif test $a -gt $b
then echo "big is: "$a
else echo "big is: "$b
fi
四、編寫函數實現數字的加減乘除運算,例如輸入1 + 2,,將得出正確結果
#!/bin/bash
source funs.sh
jia $1 $2
jian $1 $2
cheng $1 $2
chu $1 $2
funs.sh
#!bin/bash
echo "1st arg is $1"
echo "2nd arg is $2"
jia (){
local a=$[$1+$2]
echo $a
}
jian (){
local a=$[$2-$1]
echo $a
}
cheng (){
local a=$[$1*$2]
echo $a
}
chu (){
local a=$[$1/$2]
echo $a
}
五、斐波那契數列又稱黃金分割數列,因數學家列昂納多·斐波那契以兔子繁殖爲例子而引入,故又稱爲「兔子數列」,指的是這樣一個數列:0、一、一、二、三、五、八、1三、2一、3四、……,斐波納契數列以以下被以遞歸的方法定義:F(0)=0,F(1)=1,F(n)=F(n-1)+F(n-2)(n≥2)寫一個函數,求n階斐波那契數列
fact() {
if [ $1 -eq 0 ]
then
echo 0
elif [ $1 -eq 1 ]
then
echo 1
else
echo $[$(fact $[$1-2])+$(fact $[$1-1])]
fi
}
六、漢諾塔(又稱河內塔)問題是源於印度一個古老傳說。大梵天創造世界的時候作了三根金剛石柱子,在一根柱子上從下往上按照大小順序摞着64片黃金圓盤。大梵天命令婆羅門把圓盤從下面開始按大小順序從新擺放在另外一根柱子上。而且規定,在小圓盤上不能放大圓盤,在三根柱子之間一次只能移動一個圓盤。利用函數,實現N片盤的漢諾塔的移動步驟
#!/bin/bash
step=0
hanoi(){
[[ ! $1 = ~ ^[1-9][0-9]*$ ]]&&echo "error! please input a positive interger" && exit
if [ $1 -eq 1 ]; then
let step++
echo "$step: move plate $1 $2 -----> $4"
else
hanoi "$[$1-1]" $2 $4 $3
let step++
echo "$step: move plate $1 $2 -----> $4"
hanoi "$[$1-1]" $3 $2 $4
fi
}
read -p "please input the number of plates: "number
hanoi $number A B C
數組
編寫腳本,定義一個數組,數組中的元素是/var/log目錄下全部以.log結尾的文件;要統計其下標爲偶數的文件中的行數之和
#!/bin/bash
declare -a files
files=(/var/log/.log)
for i in `seq0 $[${#files[]}-1]<br/>do<br/>fileline=
wc -l ${file[$i]} |cut -d " " -f1`
[ $[$i%2] -eq 0 ] && let lines+=$fileline
done
echo "Lines: $lines."
===================================================
#!/bin/bash
declare -a files
files=(/var/log/.log)
declare -i lines=0
for i in $(seq0 $[${#files[]}-1])
do
if [ $[$i%2] -eq 0 ];then
let lines+=$(wc-l ${files[$i]} | cut -d ' ' -f1)
fi
done
echo "Lines: $lines."
一、生成10個隨機數,採用冒泡算法進行升序或降序排序
#!/bin/sh
echo "please input a number list:"
read -a arr
for (( i=0 ; i<${#arr[@]} ; i++ ))
do
for (( j=${#arr[@]}- 1 ; j>i ; j-- ))
do
#echo $j
if [[ ${arr[j]} -lt ${arr[j-1]} ]]
then
t=${arr[j]}
arr[j]=${arr[j-1]}
arr[j-1]=$t
fi
done
done
echo "after ascending sorting:"
echo ${arr[@]}
for (( i=0 ; i<${#arr[@]} ; i++ ))dofor (( j=${#arr[@]}- 1 ; j>i ; j-- ))do#echo $jif [[ ${arr[j]} -gt ${arr[j-1]} ]]thent=${arr[j]}arr[j]=${arr[j-1]}arr[j-1]=$tfidonedoneecho "after descending sorting:"echo ${arr[@]}