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).
–
MatAug 4 '12 at 13:06

@Muhammad-gelbana Does it really need to be a !? And what happens with a afterwards, does it get executed as a shell script?
–
patrixAug 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 GelbanaAug 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)?
–
patrixAug 4 '12 at 13:26

If this worked, the command in a would have @$! in double quotes, which would be problematic.
–
MatAug 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 GelbanaAug 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 GelbanaAug 4 '12 at 15:55