How to use positional parameters with “bash -c” command?

后端 未结 2 460
再見小時候
再見小時候 2020-12-31 02:30

I\'d like to know the best way of using positional parameters when using the command bash -c.

The man pages indicates for the -c option tha

2条回答
  •  [愿得一人]
    2020-12-31 03:06

    The parameter $0 is special in that it does not participate in shift (for example).

    This works as expected:

    $ bash -c 'shift; printf "%s %s %s\n" $1 $2 $3' _ par1 par2 par3 par4
    par2 par3 par4
    

    This does not:

    $ bash -c 'shift; printf "%s %s %s\n" $0 $1 $2' par1 par2 par3 par4
    par1 par3 par4
    

    This has been defined in POSIX (simplified):

    sh -c command_string [command_name [argument...]]

    The following additional options shall be supported:

    -c

    Read commands from the command_string operand. Set the value of special parameter 0 (see Special Parameters) from the value of the command_name operand and the positional parameters ($1, $2, and so on) in sequence from the remaining argument operands.

    So, use this:

    sh -c 'commands' command_name arg1 arg2 arg3 ....
    

提交回复
热议问题