bash脚本:提示用户进行确认

在bash脚本时,有时需要用户确认后才能进行下一步操作。
在这个教程中,我们将实现这一点。

需要用户确认才执行操作

创建一个bash脚本文件

vi test.sh

复制并粘贴以下内容到test.sh

#!/bin/bash

read -p "run 'uname -ar' ? (yes/no)" reply

choice=$(echo $reply|sed 's/(.*)/L1/')

if [ "$choice" = 'yes' ] 
then
  echo "you selected yes";
  sleep 3;
  uname -ar;

elif [ "$choice" = 'no'  ]
then

  echo "you selected no ";
  sleep 3
  exit 0
else
echo "type yes or no";
fi

通过reply获取用户的输入, 然后进行处理,删除前后空格,将值保存到变量choice。

授予可执行权限,并测试

chmod 700 test.sh
sh test.sh

或者

./test.sh

日期:2019-08-20 17:58:06 来源:oir作者:oir