Bash write to file without echo?

anon picture anon · Jul 1, 2012 · Viewed 135.6k times · Source

As an exercise, does a method exist to redirect a string to a file without echo? Currently I am using

echo "Hello world" > test.txt

I know about cat and printf. I was thinking something like

> test.txt <<<"Hello world"

Of course this doesnt work, but maybe a similar command?

Answer

Eric picture Eric · Mar 5, 2013

You can do this with "cat" and a here-document.

cat <<EOF > test.txt
some text
EOF

One reason for doing this would be to avoid any possibility of a password being visible in the output of ps. However, in bash and most modern shells, "echo" is a built-in command and it won't show up in ps output, so using something like this is safe (ignoring any issues with storing passwords in files, of course):

echo "$password" > test.txt