Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This line works as expected on it's own

(echo '@$X!'; sleep 3; echo '@$X!')

And I need to insert this line in a file using the following command, but it's not working. The echo'ed command must be executable.

echo "(echo '@$X!'; sleep 3; echo '@$X!') | mycmd" >> a

It keeps returning this error

sh: !': event not found

I understand that echoing a string between single quotes, inhibits any variable substituion or character escaping but I'm unable to apply that to solve this issue !

I have to do it through a command because I'll be sending it through a tool so editing the file using an editor is not an available option for me.

share|improve this question
Note: you're either not running bash, or running it in sh mode (this is visible from the error message). I'm not getting that error from bash, though the $ needs escaping (and I might have non-default options set). – Mat Aug 4 '12 at 13:06
I get the same error in bash as well – patrix Aug 4 '12 at 13:15
@Muhammad-gelbana Does it really need to be a !? And what happens with a afterwards, does it get executed as a shell script? – patrix Aug 4 '12 at 13:23
@patrix, yeah :), also the $ must be appended by a character. The file being appended will be executed on each startup and it's very important to have it this way. – Muhammad Gelbana Aug 4 '12 at 13:25
I'm just a bit worried that we are solving the wrong problem here. What's the greater picture you want to accomplish (i.e. why do you need to programmatically create a startup script in the first place)? – patrix Aug 4 '12 at 13:26
up vote 2 down vote accepted


My first thought was wrong. Explicitly quoting the bang (!) seems to work:

echo "(echo '@$'\!; sleep 3; echo '@$'\!) | mycmd" > a
share|improve this answer
If this worked, the command in a would have @$! in double quotes, which would be problematic. – Mat Aug 4 '12 at 13:07
If I switch the single and double quotes the line will be appended into the file but the echoed line won't execute. – Muhammad Gelbana Aug 4 '12 at 13:21
@Thor, I apologize for the confusion but I didn't state my complete problem. Based on your solution and the slight update within my question (i.e a character X suffixes the $), this should be the answer: echo '(echo "@\$X"\!; sleep 3; echo "@\$X"\!) | mycmd' > a. Thank you. – Muhammad Gelbana Aug 4 '12 at 15:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .