Linux – Ambiguous redirect error for simple echo

bashcommand linelinux

I have come across an oddity when performing a simple echo command. Can anyone explain what's going on? Here's the scenario, there are exactly three files in a folder and I want to replace their contents with a blank character. The files are:

ev_tracker.css  ev_tracker.html  ev_tracker.js

I tried a simple command to echo a space character to all files

$ echo \  > *

and I got the following error:

bash: *: ambiguous redirect

So, I tried to be more specific…

$ echo \  > ev_tracker.*
bash: ev_tracker.*: ambiguous redirect

And more specific still…

$ echo \  > ev_tracker.{css,html,js}
bash: ev_tracker.{css,html,js}: ambiguous redirect

Finally, I performed the action on each file, individually, without error.

$ echo \  > ev_tracker.css
$ echo \  > ev_tracker.html
$ echo \  > ev_tracker.js
$

Can anyone explain why I received the error? I'm using Ubuntu 14.04 and whatever default sh variant that it would have.

Best Answer

echo a > *

will be expanded by bash to

 echo a > ev_tracker.css ev_tracker.html ev_tracker.js

according to man bash (REDIRECTION)

The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to (...) pathname expansion (...)

If it expands to more than one word, bash reports an error.

you can use

echo a | tee * > /dev/null

see man tee, tee command is designed to do what you are looking for.

note also that

echo \ | tee * > /dev/null

will not output a backslash to files.

Related Question