Reputation: 1341
I would like to execute a (for example sed
) command and echo
it before it is executed.
I tried to save the command in a variable.
Then, echo
it and execute it:
command="sed -i 's/FOO/BAR/g' myFile";
echo "Command: \"$command\"" ;
$command ;
Error I got :
Command: "sed -i 's/FOO/BAR/g' myFile"
sed: -e expression #1, char 1: unknown command: `''
How should I escape the single quotes? (or may I use double quotes ?)
I googled it, but found no answer.
Upvotes: 2
Views: 2997
Reputation: 58589
Define a convenience function to echo any given command, then to run it.
verbosely_do () {
printf 'Command: %s\n' "$*"; # printf, not echo, because $@ might contain switches to echo
"$@";
}
verbosely_do sed -i 's/FOO/BAR/g' myFile
This will give you:
Command: sed -i s/FOO/BAR/g myFile
and then perform the sed(1) command.
Upvotes: 2
Reputation: 5307
The use of $command
bypasses the shell expansion and thus the single quotes are passed in the argument to sed
. Either loose the single quotes or use eval $command
.
Upvotes: 2
Reputation: 246837
The simple answer is to just remove the single quotes: sed is interpreting them as part of the sed program:
command="sed -i s/FOO/BAR/g myFile"
$command
That clearly won't be appropriate for more complicated sed scripts (e.g. those that include whitespace or semi-colons).
The correct answer, assuming you use a shell that has arrays (bash, ksh, zsh) is:
command=(sed -i 's/FOO/BAR/g' myFile)
echo "Command: \"${command[*]}\""
"${command[@]}" # the quotes are required here
See http://www.gnu.org/software/bash/manual/bashref.html#Arrays
Upvotes: 3