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

后端 未结 8 1712
时光说笑
时光说笑 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:28

    Whenever you see you don't get the desired output, use the following method:

    """\special character"""

    where special character may include ! " * ^ % $ # @ ....

    For instance, if you want to create a bash generating another bash file in which there is a string and you want to assign a value to that, you can have the following sample scenario:

    Area="(1250,600),(1400,750)"
    printf "SubArea="""\""""${Area}"""\""""\n" > test.sh
    printf "echo """\$"""{SubArea}" >> test.sh
    

    Then test.sh file will have the following code:

    SubArea="(1250,600),(1400,750)"
    echo ${SubArea}
    

    As a reminder to have newline \n, we should use printf.

提交回复
热议问题