1

I have this script:

cd foo && git pull && node server.js & && pid=$! && echo "$pid"

but bash doesn't seem to like this part: & &&... so I changed it into this:

set -e
cd foo
git pull
node server.js &
pid=$!
echo "$pid"

but is there a way to do it with double ampersand && instead?

Perhaps the purpose of the question is if these two are equivalent:

cd foo && git pull && node server.js & && pid=$! && echo "$pid"
cd foo && git pull && ( node server.js & ) && pid=$! && echo "$pid"

My guess is that they aren't equivalent..

2
  • yeah good eye, will fix that Sep 14, 2018 at 19:48
  • 1
    checking the return status of a backgrounded job (i.e. with &&) is pointless; from the bash manual: If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background. The shell does not wait for the command to finish, and the return status is 0 (true)
    – Jeff Schaller
    Sep 14, 2018 at 20:17

2 Answers 2

3

cmd1 && cmd2 means "do cmd1, and if it succeeded, then do cmd2". It isn't known whether a command succeeded until after it's finished running, so it doesn't make sense to both put a command in the background and make the next command's execution depend on whether the first one succeeded.

It sounds like what you actually want to do is "start cmd1 in the background, then do cmd2". This is just cmd1 & cmd2.

Thus, here's the command you want: cd foo && git pull && node server.js & pid=$! && echo "$pid"

3

Whitespace is free. IMO, for a long command list like this, newlines aid readability. Even when you want to use && for the logical meaning: for example

cd foo &&
git pull && {
    node server.js &
    pid=$!
    echo "$pid"
}

That only gets into the node block if both cd and git succeed.

In this scenario, I think that makes set -e less useful, as you're handling the return codes yourself.

2
  • not a real answer, just an extended comment. Sep 14, 2018 at 22:28
  • np, yeah the bash script I am generating is a string generated in another program, using && to join commands is simply a little bit easier, but I can use newlines in the generated script Sep 14, 2018 at 22:57

You must log in to answer this question.

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