Search code examples
shellbackground-process

Order of instructions in shell script


I have this simple shell script:

#!/bin/sh

echo "alpha"

finish()
{
    echo "--------------------------------------------------------------"
}
trap finish EXIT

echo "bravo"

cd /non/existent/path
# cd /non/existent/path && gitk &

echo "charlie"

When run, this gives the following output as expected:

alpha
bravo
./test.sh: 13: cd: can't cd to /non/existent/path
charlie
--------------------------------------------------------------

But then, if I uncomment the line containing the gitk call (i.e. line 14), I get this output:

alpha
bravo
./test.sh: 13: cd: can't cd to /non/existent/path
charlie
--------------------------------------------------------------
./test.sh: 14: cd: can't cd to /non/existent/path

Notice how the line with the dashes is no longer at the end. Any idea why this happens?

I also noticed that if I remove the ampersand at the end of that line, the order is once again as I'd expect. So starting gitk as a background process clearly has an impact, but I don't know how exactly.

Finally, is it possible to modify the script such that I can continue to start gitk as a background process but still have the line with the dashes appear at the end?


Solution

  • Behavior is as expected since You spawn a child process via &. If you wanna Your trap function to be executed after just add wait in end of Your script:

    #!/bin/sh
    
    echo "alpha"
    
    finish()
    {
        echo "--------------------------------------------------------------"
    }
    trap finish EXIT
    
    echo "bravo"
    
    cd /non/existent/path
    cd /non/existent/path && gitk &
    
    echo "charlie"
    wait
    

    That will wait on all child processes to be completed and then exits (call trap finish). Output:

    $ ./gautam.sh
    alpha
    bravo
    ./gautam.sh: line 13: cd: /non/existent/path: No such file or directory
    charlie
    ./gautam.sh: line 14: cd: /non/existent/path: No such file or directory
    --------------------------------------------------------------