linuxbash

Why does '&&' vs. '&' behave differently with the 'test' command in Bash?


Consider:

gndlp@ubuntu:~$ test -x examples.desktop && echo $?
gndlp@ubuntu:~$ test -x examples.desktop & echo $?
[1] 2992
0

Why is Bash acting the way it is in this situation?

Is the test command simply not finishing and thus the echo command isn't processed?


Solution

  • The meaning of && and & are intrinsically different.

    So looking at your example:

    gndlp@ubuntu:~$ test -x examples.desktop  && echo $?
    gndlp@ubuntu:~$ test -x examples.desktop  & echo $?
    [1] 2992
    0
    

    The first command—as it is structured—actually does not return anything. But second command returns a [1] 2992 in which the 2992 refers to the process ID (PID) that is running in the background and the 0 is the output of the first command.

    Since the second command is just running test -x examples.desktop in the background it happens quite quickly, so the process ID is spawned and gone pretty immediately.