0

I'm using this very simple bash script:

#!/bin/bash
CMD="sed -e 's/test/abz/' <test >test_res"
echo $CMD
$CMD

When I run the script I get this output:

sed -e 's/test/abz/' <test >test_res
sed: -e expression #1, char 1: unknown command: `''

If I run the exact same cmd (sed -e 's/test/abz/' test_res) on the cmd line (not in a bash script) it works just fine.

What am I doing wrong? Any help is much appreciated.

1 Answer 1

2

Don't store your arguments in a single variable as word splitting interprets quotes literally inside it. The quick hack to it is to use eval but it's not recommended:

CMD="sed -e 's/test/abz/' <test >test_res"
eval "$CMD"

You can use an array but you can only do that up to the arguments and not including the redirections:

CMD=(sed -e 's/test/abz/')
"$CMD[@]}" <test >test_res

As for the error sed: -e expression #1, char 1: unknown command: `'', it was simply because your command expanded as:

sed -e "'s/test/abz/'" "<test" ">test_res"
Sign up to request clarification or add additional context in comments.

7 Comments

+1. I might add a link to BashFAQ #50 (mywiki.wooledge.org/BashFAQ/050) for more comprehensive discussion on the topic.
@CharlesDuffy I do hope they don't add "${CMD[@]}" someday.
They already discuss the technique, but of course wouldn't use an upper-case variable name for something in neither the environment or the set of builtins. And, a second time -- if you're implying plagiarism, please be more explicit and specific to the instance. I'm not an active contributor, but I know the admin (and some of the active folks -- the creator/owner of shellcheck.net among them) and can ask what's up if anything unauthorized traces back to a non-anonymous account.
No nothing really serious. I just feel like they should give credit to all those people they took ideas with whoever they were.
Greg Wooledge was rather prolific back in the day -- most of the older content is his original work, and a significant part of the newer content is original work of Vidar Holen. Beyond that -- it's a wiki; people choose to credit themselves when they add things, or not, and if they add things that aren't their own work without credit, then taking that content down or adding credit is the appropriate course of action. Thus far, though, I've heard no foundation for the allegations repeatedly made.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.