首页 > 系统 > Linux > 正文

8个实用的Shell脚本分享

2019-10-26 18:46:08
字体:
来源:转载
供稿:网友

几个Shell脚本的例子,觉得还不错。

【例子:001】判断输入为数字,字符或其他
代码如下:
#!/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】求平均数
代码如下:
#!/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 


【例子: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" 
 
# 输出结果 
# ./namelist.sh 
name=  Jame 
name=  Bob 
name=  Tom 
name=  Jerry 
name=  Sherry 
name=  Alice 
name=  John 

【例子:005】批量测试文件是否存在
代码如下:
[root@host ~]# cat testfile.sh       
#!/bin/bash 
 
 
for file in test*.sh 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表