How to pass a parameter to a command that's being executed by exec in bash?

I’m trying to start a subprocess with a unique process name from a bash script. This works:

bash -c "exec -a MyUniqueProcessName './start_service' &"

but my problem is that I want to pass a parameter to start_service. If I do something like

bash -c "exec -a MyUniqueProcessName './start_service param' &"

or

bash -c "exec -a MyUniqueProcessName './start_service $myvar' &"

then it fails with complaining about

/start_service param: No such file or directory

What am I doing wrong?

Asked By: Adam Arold

||

exec takes the utility and its arguments as separate arguments:

bash -c "exec -a MyUniqueProcessName './start_service' 'param1' 'param2' 'etc.' &"

Testing on OpenBSD:

$ bash -c 'exec -a hello sleep 5 &' && pgrep -lf hello
1898 hello 5
$ bash -c 'exec -a hello sleep 5 &' && ps -a | grep hello
18164 p1  Sp       0:00.01 hello 5 (sleep)
26417 p1  R+/0     0:00.01 grep hello

Same tests on Ubuntu (we get something called sleep back, but we get it when querying for hello, which should be ok; Linux is a mixed bag of wierdness):

$ bash -c 'exec -a hello sleep 5 &' && pgrep -lf hello
2849889 sleep

Note the addition of -f to ps here:

$ bash -c 'exec -a hello sleep 5 &' && ps -af | grep hello
myself  2851359       1  0 17:41 pts/0    00:00:00 hello 5
myself  2851361 2848295  0 17:41 pts/0    00:00:00 grep hello
Answered By: Kusalananda
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.