linuxbashcontrol-c

Linux Bash Script: Command Executed After Control-C


My goal is to open a new terminal window, SSH into a remote machine in that window, prompt the user to continue, and then execute a command. I currently have:

gnome-terminal -t "MyWin" -x bash -c "ssh -X $USER@$REMOTE_IP 'echo \"Press ENTER to continue\" ; read JUNK ; echo \"HELLO\" > hello.txt ; bash '"

This works and achieves my primary goal.

The problem is that if the user attempts to exit the script via Control-C while waiting at the "Press ENTER..." prompt, the remainder of the command is executed (e.g., hello.txt appears on the remote machine).

Any thoughts on why this is happening and how to avoid it?

Thanks!


Solution

  • CtrlC kills the read command, not everything there, so the next command gets executed. You can use && operator to signify that the next command should be executed only if the current one exits successfully.

    gnome-terminal -t "MyWin" -x bash -c "ssh -X $USER@$REMOTE_IP 'echo \"Press ENTER to continue\" ; read JUNK && echo \"HELLO\" > hello.txt ; bash '"