In a bash script I start a new terminal with a command that gives an error. However I don't seem to be able to grab that error code:
#! /bin/bash
gnome-terminal -x bash -c "cat dksdamfasdlm"
echo $?
Output:
0
So I get the error code of the gnome-terminal
command instead of the cat
one. One suggestion I got, was to make a file with the code and read that from the parent bash. The problem is that I still seem to not be able and read the error code even that way:
#! /bin/bash
gnome-terminal -x bash -c "cat dksdamfasdlm; echo $?; sleep 2"
Output (on new terminal):
cat: dksdamfasdlm: No such file or directory
0
Why is that? Some suggestion on how to solve this? I just want to somehow grab the error in the new terminal from the parent bash.
It seems GNOME Terminal exits immediately after starting, which is obvious if you run for example gnome-terminal -x sleep 10
. Since it doesn't wait for the command to finish, there's no way the return code will be that of the command. I could find no option in gnome-terminal --help-all
to keep the process in the foreground.
Regarding your second question, you've double-quoted the command, so $?
is expanded before running it. This should work:
gnome-terminal -x bash -c 'cat dksdamfasdlm; echo $?; sleep 2'
PS: The -x
option is not documented in GNOME Terminal 3.8.4's gnome-terminal --help-all
, various references don't help much, and there's no good explanation for why there's a -e
option with identical semantics and different syntax.