whiletrue; do read -p "Do you wish to install this program? " yn case$ynin [Yy]* ) make install; break;; [Nn]* ) exit;; * ) echo"Please answer yes or no.";;; esac done
set -- $(locale LC_MESSAGES) yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"
whiletrue; do read -p "Install (${yesword} / ${noword})? " yn if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi if [[ "$yn" =~ $noexpr ]]; thenexit; fi echo"Answer ${yesword} / ${noword}." done
通过locale命令获取当前语言环境下的Yes和No的表达式和字符串,实现脚本的国际化支持。
4. POSIX通用解决方案
4.1 基本read和if...then...else组合
1 2 3 4 5 6 7 8 9
#!/bin/sh printf'Is this a good question (y/n)? ' read answer
if [ "$answer" != "${answer#[Yy]}" ] ;then echo Yes else echo No fi
4.2 单键输入功能
1 2 3 4 5 6 7 8 9
#!/bin/sh printf'Is this a good question (y/n)? ' old_stty_cfg=$(stty -g) stty raw -echo ; answer=$(head -c 1) ; stty$old_stty_cfg if [ "$answer" != "${answer#[Yy]}" ];then echo Yes else echo No fi
4.3 单键输入功能并支持国际化
1 2 3 4 5 6 7 8 9 10
#!/bin/sh yExpr=$(locale yesexpr) printf'Is this a good question (y/n)? ' old_stty_cfg=$(stty -g) stty raw -echo ; answer=$(head -c 1) ; stty$old_stty_cfg if [ "$answer" != "${answer#${yExpr#^}}" ];then echo Yes else echo No fi
verbEcho Ask for continuing askFor Do you want to continue this demonstration || exit
toInstall='' for package in moon-buggy pacman4console junior-games-text; do verbEcho Ask for Installation of $package if askFor Do I install full "$package"; then verbEcho "Add $package to list" toInstall="$toInstall$package" fi done if [ -z "$toInstall" ]; then echo Nothing to do. elif askFor Do you really want to install $toInstall; then verbEcho Proceed installation of $toInstall echosudo apt install $toInstall# Drop `echo` for real installation fi
5. 使用专用工具
1 2 3 4 5
if whiptail --yesno "Is this a good question" 20 60 ;then echo Yes else echo No fi
可以使用whiptail、dialog、gdialog、kdialog等工具创建更美观的交互界面。
6. Bash特定解决方案
6.1 基本的行内方法
1 2 3 4 5 6 7 8 9
read -p "Is this a good question (y/n)? " answer case${answer:0:1}in y|Y ) echo Yes ;; * ) echo No ;; esac
6.2 单键输入功能
1
read -n 1 -p "Is this a good question (y/n)? " answer