el-teedee
el-teedee

Reputation: 1341

Unix : saving a sed command in a variable, to echo it, then execute it

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

Answers (3)

pilcrow
pilcrow

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

Bryan Olivier
Bryan Olivier

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

glenn jackman
glenn jackman

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

Related Questions