Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'&&' vs. '&' with the 'test' command in Bash

Tags:

linux

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?

like image 911
gndlp Avatar asked Nov 06 '14 02:11

gndlp


People also ask

What are the 3 apostrophes?

The apostrophe has three uses: 1) to form possessive nouns; 2) to show the omission of letters; and 3) to indicate plurals of letters, numbers, and symbols. ​Do not ​use apostrophes to form possessive ​pronouns ​(i.e. ​his​/​her ​computer) or ​noun ​plurals that are not possessives.

What symbol is apostrophe?

An apostrophe is a punctuation mark (') that appears as part of a word to show possession, to make a plural number or to indicate the omission of one or more letters.


2 Answers

The meaning of && and & are intrinsically different.

  • What is && in Bash? In Bash—and many other programming languages—&& means “AND”. And in command execution context like this, it means items to the left as well as right of && should be run in sequence in this case.
  • What is & in Bash? And a single & means that the preceding commands—to the immediate left of the &—should simply be 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—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.

like image 127
Giacomo1968 Avatar answered Oct 16 '22 07:10

Giacomo1968


& executes a command in the background, and will return 0 regardless of its status.

From the man page:

If a command is terminated by the control operator &, the shell executes the command in the background in a subshell. The shell does not wait for the command to finish, and the return status is 0. Commands separated by a ; are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed.

like image 26
Makoto Avatar answered Oct 16 '22 09:10

Makoto