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


当前回答

绝对最简单的解决方案是这一行,没有巧妙的技巧:

read -p "press enter ..." y

它让人想起了经典的DOS点击任意键继续,除了它等待Enter键,而不仅仅是任何键。

的确,这并没有为您提供“是”“否”“取消”的三个选项,但在您接受control-C作为“否”的情况下,这很有用。在简单脚本中取消,例如:

#!/bin/sh
echo Backup this project
read -p "press enter ..." y
rsync -tavz . /media/hard_to_remember_path/backup/projects/yourproject/

因为您不需要记住难看的命令和路径,但也不需要记住运行速度过快的脚本,而不需要在您决定它不是您想要运行的脚本之前停止。

其他回答

是/否/取消

作用

#!/usr/bin/env bash
@confirm() {
  local message="$*"
  local result=''

  echo -n "> $message (Yes/No/Cancel) " >&2

  while [ -z "$result" ] ; do
    read -s -n 1 choice
    case "$choice" in
      y|Y ) result='Y' ;;
      n|N ) result='N' ;;
      c|C ) result='C' ;;
    esac
  done

  echo $result
}

用法

case $(@confirm 'Confirm?') in
  Y ) echo "Yes" ;;
  N ) echo "No" ;;
  C ) echo "Cancel" ;;
esac

使用干净的用户输入进行确认

作用

#!/usr/bin/env bash
@confirm() {
  local message="$*"
  local result=3

  echo -n "> $message (y/n) " >&2

  while [[ $result -gt 1 ]] ; do
    read -s -n 1 choice
    case "$choice" in
      y|Y ) result=0 ;;
      n|N ) result=1 ;;
    esac
  done

  return $result
}

用法

if @confirm 'Confirm?' ; then
  echo "Yes"
else
  echo "No"
fi

使用PyInquirer的一行python替代方案

python3 -c 'import PyInquirer; print(PyInquirer.prompt([{"type":"confirm", "message":"Do you want to continue?", "name":"r"}]).get("r"))'

它支持yes/no/cancel(intr,CTRL+C)。

受到@Mark和@Myrdin的回答的启发,我创建了一个通用提示的函数

uniprompt(){
    while true; do
        echo -e "$1\c"
        read opt
        array=($2)
        case "${array[@]}" in  *"$opt"*) eval "$3=$opt";return 0;; esac
        echo -e "$opt is not a correct value\n"
    done
}

这样使用:

unipromtp "Select an option: (a)-Do one (x)->Do two (f)->Do three : " "a x f" selection
echo "$selection"

我注意到,对于这样简单的用户输入,没有人发布显示多行回声菜单的答案,所以我的做法如下:

#!/bin/bash

function ask_user() {    

echo -e "
#~~~~~~~~~~~~#
| 1.) Yes    |
| 2.) No     |
| 3.) Quit   |
#~~~~~~~~~~~~#\n"

read -e -p "Select 1: " choice

if [ "$choice" == "1" ]; then

    do_something

elif [ "$choice" == "2" ]; then

    do_something_else

elif [ "$choice" == "3" ]; then

    clear && exit 0

else

    echo "Please select 1, 2, or 3." && sleep 3
    clear && ask_user

fi
}

ask_user

发布这种方法是希望有人发现它有用且省时。

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