Shell for循环和select循环语句

Shell for循环和select循环语句

罗小黑
2021-07-01 / 0 评论 / 14 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年07月05日,已超过31天没有更新,若内容或图片失效,请留言反馈。

for循环格式

for 变量名 in 变量取值列表
do 
    指令
done

示例
打印5 4 3 2 1 5个数字

#!/bin/bash
for i in 5 4 3 2 1
do
   echo $i
done
方法二
#!/bin/bash
for (( i=5;i>0;i--))
do
   echo $i
done 

PS:改名命令rename命令
jpg格式的图片改成png

rename ".jpg" ".png" "*.jpg"

打印九九乘法表

#!/bin/bash
for num1 in `seq 9`
do
    for num2 in `seq 9`
    do
        if [ $num1 -ge $num2 ];then
            if ((($num1*$num2)>9)) ;then
                echo -en "${num1}x${num2}=$((num1*num2)) "
            else
                echo -en "${num1}x${num2}=$((num1*num2))  "
            fi
        fi
    done
echo " "
done

计算1-100的和

#!/bin/bash
for ((i=1;i<=100;i++))  
do
    ((sum=sum+$i))
done
echo "$sum"

select循环语句

select 变量名 [ in 菜单取值列表]
do 
    指令
done

示例:select 循环打印简单菜单项
1、直接使用列表字符串

#!/bin/bash
select name in zhansan lisi wanger
do
    echo $name
done

2、采用数组作为变量打印

#!/bin/bash
array=(zhansan lisi wanger)
select $name in "${array[@]}"
do
  echo "$name"
done
#!/bin/bash
PS3="please select a num from menu:"     #PS3是select循环的提示符
select name in zhansan lisi wanger
do
    echo  -e "I guess you selected the menu is:\n $REPLY) $name"     #REPLY变量是菜单项对应的数字
done

示例
打印选择菜单 ,选择一键安装不同Web服务

1.[install lamp]
2.[install lnmp]
3.[exit]
#!/bin/bash
RETVAR=0
path=/server/scripts                #定义脚本路径
[ ! -d "$path" ] && mkdir $path -p  #如果不存在就创建
function Usage() {
    echo "Usage :$0 argv"
    return 1
}
function InstallService() {
    if [ $# -ne 1 ]; then
    Usage
    fi
    local RETVAR=0
    echo "start installing ${1}."
    sleep 2
    if [ ! -x "$path/${1}.sh" ]; then
        echo "$path/${1}.sh 没有执行权限"
        return 1
    else
        $path/${1}.sh
        return $RETVAR
    fi
}
function main() {
PS3="please input the num you want:"
select num in "Install lamp" "Install lnmp" "exit"
do
  case "$num" in
  "Install lamp")
      InstallService lamp
      RETVAR=$?
      ;;
  "Install lnmp")
      InstallService lnmp
      RETVAR=$?
      ;;
  exit)
      echo bye.
      return 3
      ;;
  *)
      echo "the num you input must be {1|2|3}"
      echo "Input error"
  esac
done
  echo $ RETVAR
}
main
0

评论 (0)

取消