What is the Linux equivalent to DOS pause?

前端 未结 9 437
猫巷女王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:01

    If you just need to pause a loop or script, and you're happy to press Enter instead of any key, then read on its own will do the job.

    do_stuff
    read
    do_more_stuff
    

    It's not end-user friendly, but may be enough in cases where you're writing a quick script for yourself, and you need to pause it to do something manually in the background.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-30 17:04

    Yes to using read - and there are a couple of tweaks that make it most useful in both cron and in the terminal.

    Example:

    time rsync (options)
    read -n 120 -p "Press 'Enter' to continue..." ; echo " "
    

    The -n 120 makes the read statement time out after 2 minutes so it does not block in cron.

    In terminal it gives 2 minutes to see how long the rsync command took to execute.

    Then the subsequent echo is so the subsequent bash prompt will appear on the next line.

    Otherwise it will show on the same line directly after "continue..." when Enter is pressed in terminal.

    0 讨论(0)
提交回复
热议问题