help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Quick prepend to file using echo


From: Eric Blake
Subject: Re: [Help-bash] Quick prepend to file using echo
Date: Wed, 16 May 2012 17:23:57 -0600
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:12.0) Gecko/20120430 Thunderbird/12.0.1

On 05/16/2012 05:16 PM, Chris Jones wrote:
> Using ‘echo’, it's easy to append to a file:
> 
> --------------------------------------------------------------------------------
> $ echo "// vim: set tw=80 syntax=sh:" >> ~/.bashrc
> --------------------------------------------------------------------------------
> 
> But how do you do it the other way around..? Prepend to a file so-to-speak..? 
> 
> I saw a couple of threads in stackoverflow.com with complicated one-liners and
> everybody appeared to conclude that you need a temp file anyway..
> 
> So how about:
> 
> --------------------------------------------------------------------------------
> $ echo -e "$(echo -e "// vim: set tw=80 syntax=sh: ";cat ~/.bashrc)" > 
> ~/.bashrc
> --------------------------------------------------------------------------------

'echo -e' is non-portable; you should really be using printf instead.

This command is an epic failure.  You are causing a race between the
shell truncating ~/.bashrc and the $() command substitution that spawns
cat to read the contents of ~/.bashrc.  You MUST use a temporary file
for safety.

> 
> - how does it work..? Namely why isn't the file overwritten..?

It _doesn't_ work.  It's still quite racy, where you are relying on the
process executing the $() to fire, _and_ getting far enough along to
start the cat process, _all_ before the outermost shell truncates ~/.bashrc.

> - barring a power failure while running.. could this cause data loss..?

Most certainly it will cause data loss.

> - is there a portable way to do it with printf..?

Only by using a temporary file.

THAT SAID,

if you use GNU sed, you can use the -i option for in-place editing to
insert a line before the contents, and let sed take care of the creation
of a temporary file under the hood (yes, a temporary file is _still_
involved, but at least you don't have to explicitly name it).

-- 
Eric Blake   address@hidden    +1-919-301-3266
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]