暂停执行并等待用户输入


29

我有一个正在编写的脚本,但有一个问题:我想暂停执行并等待用户输入。我以为我在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!!!!

您可能会注意到在mainmenu(主菜单)功能中,已读-n 1 -p“文本在此处”条目。根据ubuntu,这就是我遇到的问题。有人可以告诉我出什么事了吗?谢谢!


1
舍邦是错的。您正在使用bash功能,因此必须将shebang设置为#!/usr/bin/env bash#!/bin/bash
geirha 2014年

Answers:


37

应该:

read  -n 1 -p "Input Selection:" mainmenuinput

需要n标记后,因为这表示输入N个字符后要执行读取操作,请勿等待整行。检查help read获取详细信息


2
我想通了!这是正确的代码:read -n 1 -p "Input Selection:" "mainmenuinput"现在它不等待按下回车键:-)
Elliot Labs LLC

1
“非法选项-n”
ses

1
如果您只是想暂停执行并等待在for循环中继续:for $whatever; do $whatever; read -n 1 -p Continue?; done
rekciltnuc

有人可以向我解释为什么help read有效,因为help这不是程序吗?
lindhe

显然,这是Bash的事情。有关更多信息:help help
lindhe
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.