POSIX Shell: `exec` with changed arg0

I want to exec a program and control it’s arguments including arg0 and environment. Using C I could go for execve. Can I do this in POSIX shell?

Asked By: Patrick Böker


According to POSIX documentation of Special Builtin Utilities, the syntax for exec is

exec [command [argument...]]

Environment of the calling shell should be propagated to command so setting it prior to exec-ing like foo=bar exec cmd should just work. However, you might want to consider the Rationale paragraph.

Most historical implementations were not conformant in that: foo=bar
exec cmd did not pass foo to cmd.

There is also no built-in way to fiddle argv[0].
a possible workaround could consist in symlinking some_name to command prior to exec some_name (full credit to muru)

Note that bash zsh and ksh do support an extended implementation of the exec command :

exec [-cl] [-a name] [command [arguments]]

which, thanks, to the -a option enables name to stand as argv[0]

with -a argv0 set the argv[0] string of the command executed

However, neither csh nor dash nor fish support that.

Answered By: MC68020
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.