Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get return code from a program in a new terminal? (BASH "Inception")

In terminal I can easily grab the error code of a command

> cat thisdoesntexist
cat: thisdoesntexist: No such file or directory
> echo $?
1

But doing the same when I run the command in a new terminal

> gnome-terminal -e "cat thisdoesntexist"
> echo $?
0

How can I grab the error code of the command in the second case (so that it returns 1)?

like image 798
Pithikos Avatar asked Sep 19 '25 16:09

Pithikos


1 Answers

You probably have to rely on a fifo to communicate between the two shells as gnome-terminal does not seem to propagate exit status.

sh$ TMPDIR=$(mktemp -d)
sh$ F=$TMPDIR/fifo
sh$ mkfifo $F
sh$ gnome-terminal -e 'bash -c "cat thisdoesntexist; echo $? > '"$F"'"'
sh$ cat $F
1
sh$ rm -rf $TMPDIR 

Please notice: Fifo have the added benefit of being blocking. You might use regular file for simplicity, but beware of possible race conditions.

like image 152
Sylvain Leroux Avatar answered Sep 21 '25 08:09

Sylvain Leroux