lundi 20 juin 2016

Handling of '--' in arguments of /bin/sh: POSIX vs implementations by Bash/Dash/FreeBSD's sh

I want to call /bin/sh, and use the -c option to pass the command '+x', i.e., to execute a program called '+x', whose name begins with a plus sign.

Since '+x' is interpreted by /bin/sh as an option (specifically, disable the 'x' option), /bin/sh must be prevented from interpreting it as an option. I get the following different results depending on the /bin/sh I use:

(1) First variant:

/bin/sh -c -- +x

Using Dash and Bash on Linux: The command +x is executed.

Using FreeBSD's sh: The command -- is executed, and the +x option is set.

(2) Second variant:

/bin/sh -c +x

Using Dash and Bash on Linux: The +x option is set, and there is an error because the option -c is missing an argument.

Using FreeBSD's sh: The command +x is executed.

(3) Third variant:

/bin/sh -c - +x

Using Dash and Bash on Linux: +x is executed.

Using FreeBSD's sh: The command - is executed and the option +x is set.

(4) Fourth variant: (ADDED as suggested in the comments)

/bin/sh -c+x

Using Dash and Bash on Linux: Invalid/Illegal option '+'

Using FreeBSD's sh: Bad -c option


My question: What does POSIX prescribe?

I'm reading the POSIX specification for sh here: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sh.html

Quoting from it: "A single hyphen shall be treated as the first operand and then ignored. If both '-' and "--" are given as arguments, or if other operands precede the single hyphen, the results are undefined."

I'm not sure whether that quote also applies to a single dash placed just after '-c'.

So, which one is right, Dash/Bash or FreeBSD? Or, if both are right because POSIX allows both, how to do this portably?

Aucun commentaire:

Enregistrer un commentaire