8

If I call a command (in my case another script) with xterm like so:

xterm -e sh second.sh

The value in $? after xterm returns is the exit status code of xterm (usually for me 0) and not my script.

Is there anyway to get the exit status code of my script?

neildeadman
  • 3,974
  • 13
  • 42
  • 55

1 Answers1

7

You could do something like this:

statusfile=$(mktemp)
xterm -e sh -c 'yourcommand; echo $? > '$statusfile
status=$(cat $statusfile)
rm $statusfile

The exit status of yourcommand is now in variable status.

Staven
  • 3,113
  • 16
  • 20
  • 2
    +1. There appears to be no way to have `xterm` report the command's status directly. – Fred Foo Dec 07 '11 at 14:17
  • To test, I created a script that just 'exit 0'. I then call this script instead of yourcommand. Exit code is always 127. If I replace yourcommand with, say, 'sleep 10' then the exit code is correct :S – neildeadman Dec 07 '11 at 14:32
  • This works, thanks. But I don't understand the syntax. Why is it `echo $? > '$statusfile`? The redirection (>) is part of the `sh`, and file to redirect to isn't written there, but as part of the xterm?? – Zvika Mar 05 '17 at 11:39
  • @Zvika The variable `$statusfile` contains the filename of the temp-file and the shell needs to expand it prior to giving that as part of the `-c`-argument to xterm. Please note, there is no space between `'` and `$statusfile` which means the expanded `$statusfile` will be concatenated to `'yourcommand; echo $? > '` by the shell. Also, I would write `"$statusfile"` in order to prevent the shell from interpreting anything in $statusfile. An alternative way to write that would be: `"yourcommand; echo \$? > $statusfile"` or better yet `"yourcommand; echo \$? > '$statusfile'"`. – Bodo Thiesen Oct 21 '20 at 05:36
  • what if i need to pass some variable into xterm and single quote is not an option? – user466130 Jun 02 '21 at 06:27