POSIX sh equivalent for Bash’s printf %q

前端 未结 4 1506
我寻月下人不归
我寻月下人不归 2020-12-05 05:36

Suppose I have a #!/bin/sh script which can take a variety of positional parameters, some of which may include spaces, either/both kinds of quotes, etc. I want

4条回答
  •  天命终不由人
    2020-12-05 05:37

    I think this is POSIX. It works by clearing $@ after expanding it for the for loop, but only once so that we can iteratively build it back up (in reverse) using set.

    flag=0
    for i in "$@"; do
        [ "$flag" -eq 0 ] && shift $#
        set -- "$i" "$@"
        flag=1
    done
    
    echo "$@"   # To see that "$@" has indeed been reversed
    ls "$@"
    

    I realize reversing the arguments was just an example, but you may be able to use this trick of set -- "$arg" "$@" or set -- "$@" "$arg" in other situations.

    And yes, I realize I may have just reimplemented (poorly) ormaaj's Push.

提交回复
热议问题