1. 简单模板
choose_environment() { # 重新选择 reselect=${1} if [ $reselect == 0 ];then echo '请选择要操作的环境: ' elif [ $$reselect == 1 ];then echo '请重新选择要操作的环境: ' fi echo '1.开发环境' echo '2.测试环境' echo 'q.结束' # 获取用户的输入 read -p '请输入序号, 选择环境: ' -n 1 environmentnum echo '\n' # 这里注意,判断空必须加双引号,双引号识别为没有内容;主要处理没有输入指令直接回车 if [ -z "$environmentnum" ];then choose_environment 0 elif [ $environmentnum == 1 ];then echo '进入开发环境操作' elif [ $environmentnum == 2 ];then echo '进入测试环境操作' elif [ $environmentnum == 'q' ];then echo '欢迎再次使用' # 结束脚本执行 exit 1 else echo '不支持的序号' echo $environmentnum choose_environment 1 fi } choose_environment 0
上面部分代码写了注释:
reselect: 是接受传递进来的第一个参数的变量;通过 ${数字} 的语法去接受参数;
if, elif, else, fi: 是流程控制指令; [ $reselect == 0 ] 是用来做判断;在脚本中使用变量,要使用 $ 变量名的方式; 判断语句必须和中括号之间存在一个空格;
== 是做值判断; 分号是判断语句结束标志; [ -z “$environmentnum” ] 这里的 -z 是判断变量值是否为空; then 后面跟进入判断语句的执行内容; fi 是流程控制语句的结束标志,在一个流程控制中必须存在,和 if 成对出现;
echo一般是做内容输出到命令行;
(read -p '请输入序号, 选择环境: ’ -n 1 environmentnum): read 是用来读取用户在命令行的输入;
-p 后面跟的是提示文案;
-n 后面跟的是限定输入字符个数; environmentnum 是用来接受用户在命令行输入的内容
choose_environment choose_environment(): 是定义的函数 choose_environment 0: 是调用函数代码,其中 0 是第一个传递参数的值;
2. 使用用例
OPTION=$(whiptail --title "zhaoshuangjian Menu Dialog" --menu "Choose your option" 15 60 4 \ "1" "restart zookeeper" \ "2" "manager kill-tar-start" \ "3" "预留" \ "4" "预留" 3>&1 1>&2 2>&3) managerpath=/home/zhaosj/dsp/ managerfolder="$managerpath/tongdsp.manager-3.1.0/" zookeeperpath=/home/zhaosj/zookeeper01/bin/ exitstatus=$? if [ $exitstatus = 0 ]; then if [[ $OPTION = 1 ]]; then # 查询进程 # process=`ps -ef | grep "zookeeper01" | grep -v grep | awk '{print $2}'` # 如果进程存在,则结束该进程 # if [[ -n "$process" ]]; then # echo "zookeeper process id is $process" # kill $process # fi # 启动zookeeper $zookeeperpath/zkServer.sh restart # 查询进程 process=`ps -ef | grep "zookeeper01" | grep -v grep | awk '{print $2}'` # 如果进程存在,说明启动成功 if [[ -n "$process" ]]; then # zookeeper启动成功 echo "zookeeper $process process is running !" else # zookeeper启动失败 echo "zookeeper $process process is fail !" fi elif [ $OPTION == 2 ];then if [[ -d "$managerfolder" ]]; then # stop manager process sh "$managerfolder/bin/shutdown.sh" # delete manager folder rm -rf "$managerfolder" # tar manager folder tar -zxvf "$managerpath/tongdsp.manager-3.1.0.tar.gz" # copy license.dat cp -r "$managerpath/license.dat" "$managerfolder" # start manager process sh "$managerfolder/bin/startup.sh" # 查询manager进程 process=`ps -ef|grep "tongdsp.manager-3.1.0"|grep -v grep | awk '{print $2}'` # 如果进程存在,说明启动成功 if [[ -n "$process" ]]; then # manager启动成功 echo "manager $process process is running !" else # manager启动失败 echo "manager $process process is fail !" fi fi fi else echo "You chose Cancel." fi```