When trying to get the PID of a shell command, it is possible using a script file:
#!/bin/bash
ls -lha &
echo "$!"
However, it is not possible using only the terminal.
/bin/bash -c 'ls -lha & ; echo "$!"'
This returns the error:
> /bin/bash: -c: line 1: syntax error near unexpected token `;'
The manual states the following:
> A *list* is a sequence of one or more pipelines
separated by one of the operators ;
, &
, &&
, or ||
,
and optionally terminated by one of ;
, &
, or ``.
Of these list operators, &&
and ||
have equal precedence,
followed by ;
and &
, which have equal precedence.
>
>A sequence of one or more newlines may appear in a *list*
instead of a semicolon to delimit commands.
>
> 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.
So I also tried using newline, but was not able to use it:
/bin/bash -c 'ls -lha & \n echo "$!"'
### How can I call a shell command to run on background and get the PID?
P.S.: I will not use ls
command and it is a more complex script.
This is just a minimal example to reproduce the problem.
Asked by danieltakeshi
(131 rep)
Dec 5, 2024, 07:15 PM
Last activity: Dec 5, 2024, 10:58 PM
Last activity: Dec 5, 2024, 10:58 PM