'&&' vs. '&' 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 does Bash behave as he is in this situation?

The test command simply does not complete, and therefore the echo command is not processed?

+19
source share
3 answers

The meanings of && and & are essentially different.

  • What is && in Bash? In Bash - and in many other programming languages ​​- && means "AND." And in the context of executing a command like this, this means that the elements to the left and right of && must be executed sequentially in this case.
  • What is & in Bash? And one & means that previous commands - directly to the left of & - just have to run in the background.

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 - how it is structured - actually returns nothing. But the second command returns [1] 2992 , in which 2992 refers to the process identifier (PID), which runs in the background, and 0 is the output of the first command.

Since the second command just runs test -x examples.desktop in the background, this happens pretty quickly, so the process ID is generated and immediately disappears.

+40
source

& executes the command in the background and returns 0 regardless of its status.

From the man page:

If the command terminates with the & amp; control statement, the shell executes the command in the background in a subshell. The shell does not wait for the command to complete and status 0 is returned. Commands separated by a; performed sequentially; the shell waits for each command to complete in turn. The return status is the exit status of the last command executed.

+9
source

See what your commands are:

 test -x examples.desktop && echo $? 

This means that you need to check if examples.desktop is executable, and if so, do echo $? .

 test -x examples.desktop & echo $? 

means checking to see if examples.desktop is executable and running it in the background. Then do echo $? .

+3
source

Source: https://habr.com/ru/post/1206312/


All Articles