Reading quoted/escaped arguments correctly from a string

前端 未结 4 1596
难免孤独
难免孤独 2020-11-22 03:48

I\'m encountering an issue passing an argument to a command in a Bash script.

poc.sh:

#!/bin/bash

ARGS=\'\"hi there\" test\'
./swap ${ARGS}
<         


        
4条回答
  •  长情又很酷
    2020-11-22 04:21

    Embedded quotes do not protect whitespace; they are treated literally. Use an array in bash:

    args=( "hi there" test)
    ./swap "${args[@]}"
    

    In POSIX shell, you are stuck using eval (which is why most shells support arrays).

    args='"hi there" test'
    eval "./swap $args"
    

    As usual, be very sure you know the contents of $args and understand how the resulting string will be parsed before using eval.

提交回复
热议问题