Categories
How To

Unix One Liner – Writing to a file

Sometimes the simple tasks are ones I’ll spend a long time on trying to automate rather than do it the long way. This was an effort to shorten 7 commands to 3.

In 2010, I had to log into 100 odd accounts and edit the .profile file so that the line ‘cd ~’ was included. Sounds time consuming, doesn’t it? I couldn’t use a for-loop to log into the accounts, but since they were named ‘test001’ through ‘test100’ and they all had my sudo password saved, it was pretty easy to sort out what I needed. And by easy I mean I pled to Twitter and got stumped on ‘cat’ for a long time until, finally, I wondered if echo worked the way I thought it did.

It does perplex me that ‘write’ doesn’t. I mean… it should, right? ‘write filename content’ but no. Not so much. And even echo doesn’t format the way I’d expected! It’s

echo CONTENT >> FILENAME

Oh Unix, I love you so.

sudo su - test001
echo "cd ~" >> .profile
exit

The trick was remembering that echo … echos. So if I’d use echo cd ~ >> .profile I would have ended up with cd /usr/home/account/ in my .profile, which I didn’t want. The other trick was remembering that the >> part means ‘Add to’ so if the file DID exist (it never did) it would add this to the end on a new line.

So it only took me 5 minutes instead of the far longer way!

sudo su - test001
vi .profile
a
cd ~
[esc]
ZZ
exit

And yes, I did make a for-loop ‘for test001 through test100…’ though this ended up not working as well as I wanted it to, when I found some of the older accounts were named tst099 and test_100 for some reason. Ahh, scripting. You work so well when everyone else is consistent.