幾個(gè)Shell腳本的例子,覺(jué)得還不錯(cuò)。
【例子:001】判斷輸入為數(shù)字,字符或其他
 代碼如下:
#!/bin/bash  
read -p "Enter a number or string here:" input  
  
case $input in  
   [0-9]) echo -e "Good job, Your input is a numberic! /n" ;;  
[a-zA-Z]) echo -e "Good job, Your input is a character! /n" ;;  
       *) echo -e "Your input is wrong, input again!   /n"  ;;  
esac  
【例子:002】求平均數(shù)
 代碼如下:
#!/bin/bash  
  
# Calculate the average of a series of numbers.  
  
SCORE="0"  
AVERAGE="0"  
SUM="0"  
NUM="0"  
  
while true; do  
  
  echo -n "Enter your score [0-100%] ('q' for quit): "; read SCORE;  
  
  if (("$SCORE" < "0"))  || (("$SCORE" > "100")); then  
    echo "Be serious.  Common, try again: "  
  elif [ "$SCORE" == "q" ]; then  
    echo "Average rating: $AVERAGE%."  
    break  
  else  
    SUM=$[$SUM + $SCORE]  
    NUM=$[$NUM + 1]  
    AVERAGE=$[$SUM / $NUM]  
  fi  
  
done  
  
echo "Exiting."  
【例子:003】自減輸出
 代碼如下:
[scriptname: doit.sh]  
while (( $# > 0 ))  
do  
  echo $*  
  shift  
done   
          
/> ./doit.sh a b c d e  
a b c d e  
b c d e  
c d e  
d e  
e  
【例子:004】在文件中添加前綴
 代碼如下:
# 人名列表  
# cat namelist  
Jame  
Bob  
Tom  
Jerry  
Sherry  
Alice  
John  
  
# 腳本程序  
# cat namelist.sh  
#!/bin/bash  
for name in $(cat namelist)  
do  
        echo "name= " $name  
done  
echo "The name is out of namelist file"  
  
# 輸出結(jié)果  
# ./namelist.sh  
name=  Jame  
name=  Bob  
name=  Tom  
name=  Jerry  
name=  Sherry  
name=  Alice  
name=  John  
【例子:005】批量測(cè)試文件是否存在
 代碼如下:
[root@host ~]# cat testfile.sh        
#!/bin/bash  
  
  
for file in test*.sh              
新聞熱點(diǎn)
疑難解答
網(wǎng)友關(guān)注