How to preserve double quotes in $@ in a shell script?

前端 未结 5 754
清歌不尽
清歌不尽 2020-12-10 13:59

Let\'s say I have a really simple shell script \'foo\':

  #!/bin/sh
  echo $@

If I invoke it like so:

  foo 1 2 3
         


        
5条回答
  •  轮回少年
    2020-12-10 14:13

    Let's suppose you are in a more rigid set-up and you CANNOT change your command line, and make it more "friendly" by escaping the double quotes. For example:

    example_script.sh argument_without_quotes "argument with quotes i cannot escape"
    

    First consider that inside your script you can't tell if an argument is passed with or without quotes, because the shell strips them.

    So what you can possibly do is rebuilding double quotes for arguments containing whitespaces

    This example rebuilds the whole command line, double-quoting arguments that have white spaces

    #!/bin/sh
    #initialize the variable that will contain the whole argument string
    argList=""
    #iterate on each argument
    for arg in "$@"
    do
      #if an argument contains a white space, enclose it in double quotes and append to the list
      #otherwise simply append the argument to the list
      if echo $arg | grep -q " "; then
       argList="$argList \"$arg\""
      else
       argList="$argList $arg"
      fi
    done
    
    #remove a possible trailing space at the beginning of the list
    argList=$(echo $argList | sed 's/^ *//')
    
    #pass your argument list WITH QUOTES
    echo "my_executable" $argList
    #my_executable $argList
    

    Note this limitation. If you run this example

    example_script.sh "argument with spaces" argument_without_spaces "argument_doublequoted_but_without_spaces"
    

    you will get this output

    my_executable "argument with spaces" argument_without_spaces argument_doublequoted_but_without_spaces
    

    Note the last argument: since it had no spaces, it has not been enclosed again in double quotes, but this shouldn't be an issue.

提交回复
热议问题