暂停执行并等待用户输入

Ell*_*LLC 41 bash

我有一个正在制作的脚本,但我遇到了一个问题:我想暂停执行并等待用户输入。我以为我有这个read -p -n 1 $foo命令,但系统有这个命令的问题。这是我当前的脚本:

#!/bin/sh

# Ititialization

mainmenu () {
  echo "Press 1 to update your system"
  echo "Press 2 to install samba"
  echo "Press 3 to install vsFTPd"
  echo "Press 4 to install the current version of Webmin"
  echo "Press 5 to configure samba for Active Directory"
  echo "Press x to exit the script"
  read -n 1 -p "Input Selection:" mainmenuinput
  if [ "$mainmenuinput" = "1" ]; then
            updatesystem
        elif [ "$mainmenuinput" = "2" ]; then
            installsamba
        elif [ "$mainmenuinput" = "3" ]; then
            installvsftpd
        elif [ "$mainmenuinput" = "4" ]; then
            installwebmin
        elif [ "$mainmenuinput" = "5" ]; then
            configuresambaforactivedirectory
        elif [ "$mainmenuinput" = "x" ];then
            quitprogram
        elif [ "$mainmenuinput" = "X" ];then
            quitprogram
        else
            echo "You have entered an invallid selection!"
            echo "Please try again!"
            echo ""
            echo "Press any key to continue..."
            read -n 1
            clear
            mainmenu
        fi
}

# This builds the main menu and routs the user to the function selected.

mainmenu

# This executes the main menu function.
# Let the fun begin!!!! WOOT WOOT!!!!
Run Code Online (Sandbox Code Playgroud)

您可能会在主菜单功能中注意到 read -n 1 -p "text go here" 条目。根据ubuntu,这就是我遇到问题的地方。有人能告诉我出了什么问题吗?谢谢!

NGR*_*des 56

应该:

read  -n 1 -p "Input Selection:" mainmenuinput
Run Code Online (Sandbox Code Playgroud)

需要将n标志放在后面,因为这是告诉 read 在输入N 个字符后执行,不要等待整行。检查help read这个细节

  • “非法选项-n” (3认同)
  • 我已经想通了!这是正确的代码:`read -n 1 -p "Input Selection:" "mainmenuinput"` 它现在不等待按下回车/返回键:-) (2认同)
  • 如果你只是想暂停执行并等待在 for 循环中继续:`for $whatever; 做任何事情;阅读 -n 1 -p 继续?完成` (2认同)