I have a Bash script where I want to keep quotes in the arguments passed.
Example:
./test.sh this is "some test"
then I want to use those arguments, and re-use them, including quotes and quotes around the whole argument list.
I tried using \"$@\"
, but that removes the quotes inside the list.
How do I accomplish this?
If you want to print double quote in the output then you have to use the backslash (\) with the string. In a similar way, you can print backticks (`) and backslash(\) characters in the output by using the backslash(\) within the double quotation.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
To print a double quote, enclose it within single quotes or escape it with the backslash character. Display a line of text containing a single quote. To print a single quote, enclose it within double quotes or use the ANSI-C Quoting .
3.1.2.3 Double Quotes Enclosing characters in double quotes (' " ') preserves the literal value of all characters within the quotes, with the exception of ' $ ', ' ` ', ' \ ', and, when history expansion is enabled, ' ! '. When the shell is in POSIX mode (see Bash POSIX Mode), the ' !
using "$@"
will substitute the arguments as a list, without re-splitting them on whitespace (they were split once when the shell script was invoked), which is generally exactly what you want if you just want to re-pass the arguments to another program.
Note that this is a special form and is only recognized as such if it appears exactly this way. If you add anything else in the quotes the result will get combined into a single argument.
What are you trying to do and in what way is it not working?
There are two safe ways to do this:
${variable@Q}:
When expanding a variable via ${variable@Q}
:
The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
Example:
$ expand-q() { for i; do echo ${i@Q}; done; } # Same as for `i in "$@"`...
$ expand-q word "two words" 'new
> line' "single'quote" 'double"quote'
word
'two words'
$'new\nline'
'single'\''quote'
'double"quote'
printf %q "$quote-me"
printf
supports quoting internally. The manual's entry for printf
says:
%q
Causes printf to output the corresponding argument in a format that can be reused as shell input.
Example:
$ cat test.sh
#!/bin/bash
printf "%q\n" "$@"
$
$ ./test.sh this is "some test" 'new
>line' "single'quote" 'double"quote'
this
is
some\ test
$'new\nline'
single\'quote
double\"quote
$
Note the 2nd way is a bit cleaner if displaying the quoted text to a human.
Related: For bash, POSIX sh and zsh: Quote string with single quotes rather than backslashes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With