What is the Linux equivalent to DOS pause?

前端 未结 9 516
猫巷女王i
猫巷女王i 2020-11-30 16:15

I have a Bash shell script in which I would like to pause execution until the user presses a key. In DOS, this is easily accomplished with the \"pause\" command. Is there a

9条回答
  •  攒了一身酷
    2020-11-30 17:04

    read does this:

    user@host:~$ read -n1 -r -p "Press any key to continue..." key
    [...]
    user@host:~$ 
    

    The -n1 specifies that it only waits for a single character. The -r puts it into raw mode, which is necessary because otherwise, if you press something like backslash, it doesn't register until you hit the next key. The -p specifies the prompt, which must be quoted if it contains spaces. The key argument is only necessary if you want to know which key they pressed, in which case you can access it through $key.

    If you are using Bash, you can also specify a timeout with -t, which causes read to return a failure when a key isn't pressed. So for example:

    read -t5 -n1 -r -p 'Press any key in the next five seconds...' key
    if [ "$?" -eq "0" ]; then
        echo 'A key was pressed.'
    else
        echo 'No key was pressed.'
    fi
    

提交回复
热议问题