I have a bash variable which is stored as
var="\"abc\""
So, when i locally print this variable it gives me proper output(with double quotes)
echo "$var"
"abc"
What, I want to do is print it using 'bash -c' option.. but when I do the same, it prints only value without double quotes.
bash -c "echo \"$var\""
abc
bash -c "echo $var"
abc
Can anyone help me on how to preserve the double quotes in my string, when I use it in 'bash -c'. And what does -c actually mean?
CodePudding user response:
In the statement
bash -c "echo $var"
the following happens:
(1) var
is expanded (resulting into "abc"
including the quotes).
(2) A bash child process is invoked, receiving as first parameter -c
and as second paramter echo "abc"
(3) This child process runs the command, i.e. echo "abc"
, and according to the rules about quote removal, this is equivalent to echo abc
, and you don't see any quotes in the output.
You may be tempted to do a
bash -c 'echo "$var"'
instead. In this case, the following happens:
(1) A bash child process is invoked, receiving as first parameter -c
and as second paramter echo "$var"
. Note that $var
is not expanded yet, because it is between single quotes.
(2) This child process runs the command, i.e. echo "$var"
. However, since we are in a child process, the variable var
does not exist, and the command is equivalent to echo ""
, i.e. only a newline is printed.
You can however combine both solution by doing a
export var
bash -c 'echo "$var"'
In this case, var
is made available to the child processes of your script, and you will see the quotes being printed.
CodePudding user response:
From info bash
-c If the -c option is present, then commands are read from the first non-option argument command_string.
If there are arguments after the command_string, the first argument is assigned to $0 and any remaining arguments are assigned to the positional parameters.
So the -c
option executes the commands within the quotes.
To preserve your double quotes while calling via bash -c
, you would need to quote the variable seperately.
$ bash -c "echo '"$var"'"
"abc"