Ubuntu – Run in terminal not working

bashcommand lineexecute-command

I am new to Ubuntu and I was trying to run this script:

#!/usr/bin/env bash
echo hello world

It works fine if I open the terminal first and manually invoke it. Like ./test.
I have set "Ask each time" in file prefs:
enter image description here

This also works fine:
enter image description here

Now I click Run in terminal. And Lo! Nothing happens.
I expect it to open the terminal and echo hello world. What am I doing wrong?
This is a fresh installation of ubuntu along with windows from the ubuntu website.

Best Answer

Your problem:

The problem is that echo hello world executes within milliseconds, faster than the terminal window is able to pop up.

This means your script already exits before the terminal is visible and therefore its startup is cancelled and you see nothing.

Solution 1 - modify script and add a delay:

You can add a delay (here: 5 seconds) at the end of your script so that it runs longer and you have time to view the result before the script quits and the terminal window closes itself:

#!/usr/bin/env bash
echo hello world
sleep 5

Solution 2 - modify script and wait for a keypress:

You can also add a read command to the end of your script to wait for keyboard input before the script exits.

The -s parameter causes silent input i.e. your pressed key will not be echoed to the terminal.
-n1 lets it read only one single character and returns immediately afterwards instead of waiting for Enter to be pressed.
The -p "Press any key to exit..." argument actually specifies the text to print before waiting for input.

#!/usr/bin/env bash
echo hello world
read -s -n1 -p "Press any key to exit..."

Solution 3 - change gnome-terminal's preference to keep the window open:

Launch a gnome-terminal window, open the Edit menu and select Profile preferences. Navigate to the Commands tab. You will see a drop-down menu labelled When command exits:

enter image description here

Pick Hold terminal open here and close the settings window.

From now on when you double-click on a script and select to run it in a terminal, the window will no longer close itself but stay open and display a banner informing you about the script's exit status:

enter image description here

Warning!
This setting also applies if you manually open a terminal window and try to close it by exiting Bash using the exit command or Ctrl+D - I find it pretty annoying that the terminal window does not close any more then as well.

Related Question