How can I escape an arbitrary string for use as a command line argument in Bash?

后端 未结 8 1760
时光说笑
时光说笑 2020-12-08 13:44

I have a list of strings and I want to pass those strings as arguments in a single Bash command line call. For simple alphanumeric strings it suffices to just pass them verb

8条回答
  •  眼角桃花
    2020-12-08 14:21

    FWIW, I wrote this function that invokes a set of arguments using different credentials. The su command required serializing all the arguments, which required escaping them all, which I did with the printf idiom suggested above.

    $ escape_args_then_call_as myname whoami

    escape_args_then_call_as() {
        local user=$1
        shift
    
        local -a args
        for i in "$@"; do
            args+=( $(printf %q "${i}") )
        done
    
        sudo su "${user}" -c "${args[*]}"
    }
    

提交回复
热议问题