Can I make a script wait for a key press when it has opened itself in a new terminal window?

5,692

Cannot reproduce. This code

#!/bin/bash
if [ ! -t 0 ]; then x-terminal-emulator -e "$0"; exit 0; fi
echo "new window"
read -n1 -r -p "Press any key to continue..." key
echo bye

when run with ./foo.sh </dev/null opens in a new terminal and waits for a key press.

You'll need to be more explicit about your code.

Share:
5,692
Admin
Author by

Admin

Updated on September 18, 2022

Comments

  • Admin
    Admin over 1 year

    I came across this line

    if [ ! -t 0 ]; then x-terminal-emulator -e "$0"; exit 0; fi
    

    which I can write at the top of a script and when clicking on the script file in nautilus, the script will open itself in a terminal window so that I can see the output.

    Now there is the problem that this command

    read -n1 -r -p "Press any key to continue..." key
    

    in this case will not wait for a key press.

    My guess is that x-terminal-emulator may be the reason, but I haven't found any other solution to double click a script file in Nautilus and get a new terminal window where the script will run.

    • Terrance
      Terrance about 6 years
      Your line is sooooo close: read -n 1 -s -r -p "Press any key to continue..."
    • Admin
      Admin about 6 years
      @Terrance I've copied your line into the script but it does not wait.
    • Terrance
      Terrance about 6 years
      If you copy and paste to a cli it works fine. Are you adding it to a function in your script?
    • Admin
      Admin about 6 years
      It's standing in the main part. I've tried just "read key" which seems to work, I guess that is a solution, although I don't know why.
    • Terrance
      Terrance about 6 years
      Is your script starting with #!/bin/sh or #!/bin/bash? The read commands are different per shell.
    • Admin
      Admin about 6 years
      It did not start with any of these which apparently caused trouble together with read -n1.
    • Terrance
      Terrance about 6 years
      -n 1 works fine in every test I have thrown at it as long as it is bash. Next time, please add your script to the question so that we can help assist you better.
  • Admin
    Admin about 6 years
    You're right. Found out I left out #!/bin/bash and used -n1 in the read command, and then it will not work.