Bash executing multiple commands in background in

2020-03-30 02:50发布

问题:

When i try to execute

-bash-3.2$ cd /scratch/;nohup sh xyz.sh>>del.txt &;exit

I am getting following error..

-bash: syntax error near unexpected token `;'

I am trying to run a detached process using nohup .. & . ';' works fine for all other commands except nohup sh xyz.sh>>del.txt &;

can anyone tell the problem here . Thanks

回答1:

New answer: as @CharlesDuffy correctly remarked; my old answer created a subshell, which is entirely unnecessary. In fact the & sign also terminates the line; so no more need to add an extra ;. Bash is complaining because a single line containing only a ; is not a valid command. Bash reads your command as:

cd /scratch/
nohup sh xyz.sh>>del.txt &
;
exit

Therefore you should just remove the ; after your nohup line, and (again; thanks @CharlesDuffy); only call the nohup command if you succeeded to enter the /scratch/ directory; using && means the next command is executed only if the first one succeeds.

cd /scratch/ && nohup sh xyz.sh>>del.txt & exit

Old answer:

You can try putting your command between quotes if you are in a bash shell

cd /scratch/ ; `nohup sh xyz.sh>>del.txt &` ; exit

you can take a look at this question



回答2:

As per the bash manpage:

A list is a sequence of one or more pipelines separated by one of the operators ;, &, &&, or ||, and optionally terminated by one of ;, &, or <newline>.

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.

You can see there that & isn't just something that runs a command in the background, it's actually a separator as well. Hence, you don't need the semicolon following it. In fact, it's actually invalid to try that, just the same as if you put two semicolons in sequence, the actual problem being that bash does not permit empty commands:

pax> echo 1 ; echo 2
1
2

pax> echo 1 ; ; echo 2
bash: syntax error near unexpected token ';'

You can see how this works from the following transcript, where the second and third dates are not separated because the sleep 10 runs in the background:

pax> date ; sleep 5 ; date ; sleep 10 & date ; wait
Thursday 5 April  09:04:07 AWST 2018
Thursday 5 April  09:04:12 AWST 2018
[1] 28999
Thursday 5 April  09:04:12 AWST 2018
[1]+  Done                    sleep 10


标签: bash shell