I run the following:

echo "while emacs;do echo $?;done;echo Exit code: $?;" | bash

If I exit emacs through the menu or the close button, it prints exit code 0 and restarts.

If I exit emacs through typing (kill-emacs 1) ctrl-x ctrl-e

Emacs is killed and the loop is killed as well, but the exit code is still 0.

What is causing it to break out of the loop?

UPDATE: As per pqnet's advice I used single quotes instead, the code now reads:

echo 'while emacs;do echo Exit code: $?;done;echo "Exit code: $?";echo "Loop End."' | bash

This produces the same result. I assume I need to save the value of the pid within the while loop. So I try:

echo 'while epid=$(emacs);do echo Exit code: $epid;done;echo "Exit code: $epid";echo "Loop End."' | bash

If these results are to be trusted then exit code in both cases is an empty string (or invisible binary), but I don't think that's correct either? Is my asusmption of the 'return value' being an exit code an incorrect one, or just that epid is not capturing it?

UPDATE: One of the answers explained why I wasn't getting the expected results, but now I am curious to know what code would allow me to view the exit code of emacs, since none of what I've come up with does that.

  • 1
    You're echo-ing the exit code of the while loop.
    – lcd047
    Jul 3, 2015 at 12:57
  • 1
    using double quotes will have $? expanded before executing echo or bash. Try escaping the $ to \$ or use single quotes
    – pqnet
    Jul 3, 2015 at 13:30
  • I made some adjustments to the original post, let me know if you have any advice.
    – Rob F
    Jul 3, 2015 at 16:33

2 Answers 2




The syntax of the while command is:

while test-commands; do consequent-commands; done

Execute consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed.

If you want to acquire a return value from test-commands, you'll need to assign it to another variable explicitly:


        ((ret == 0))
        echo "Exit code: $ret"
echo "Exit code: $ret"
echo "Loop End."
  • 1
    Why would I RTFM when you just helpfully made it so I don't have to?
    – Rob F
    Jul 3, 2015 at 17:34
  • @RobF Revised to answer your new question.
    – yaegashi
    Jul 3, 2015 at 19:33

Your while loop evaluates on a boolean value. In this case you could also read it as while true or while 0. So if emacs returns another value like 1 if it is killed the loop ends.

  • That part is intended, which is why I print the exit code twice. Just wanted to know why emacs returned zero in both cases and I think I may have gotten my answer above.
    – Rob F
    Jul 3, 2015 at 16:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .