我想暂停shell脚本中的输入,并提示用户进行选择。标准的是、否或取消类型问题。如何在典型的bash提示符中完成此操作?


当前回答

检查此项

read -p "Continue? (y/n): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

其他回答

您可以编写一个函数来测试:

confirm() {
  local ans IFS=;
  while read -rp "$1" -n1 ans;
  do printf '\n';
    case $ans in [Yy]) return 0;;
      [Nn]) return 1;;
    esac;
  done;
}; ## Usage: if confirm "Are you sure? "; then ...

if confirm "Does everything look ok...reboot now? [Y/n]"; then
  echo "rebooting..."
  sleep 5
  reboot
fi

我建议你使用对话框。。。

Linux学徒:使用对话框改进Bash Shell脚本对话框命令允许在shell脚本中使用窗口框,以使其使用更具交互性。

它简单易用,还有一个名为gdialog的gnome版本,它采用了完全相同的参数,但在X上显示了GUI风格。

echo "Please enter some input: "
read input_variable
echo "You entered: $input_variable"

我为回答是/否问题编写了一个小脚本:https://github.com/optimistiCli/getans

例子:

#!/bin/bash

if ! getans.sh 'Shall we proceed?' y ; then
    echo "User said “NO”"
    exit 1
fi

echo "User said “YES”"
# do something usefull
exit 0

直接链接:https://github.com/optimistiCli/getans/raw/main/getans.sh

一种简单的方法是使用xargs-p或gnu-parallel-interactive。

我更喜欢xargs的行为,因为它像其他交互式unix命令一样,在提示符后立即执行每个命令,而不是收集yes以在最后运行。(在完成所需任务后,可以按Ctrl-C键。)

例如。,

echo *.xml | xargs -p -n 1 -J {} mv {} backup/