Linux Geek‎ > ‎

[bash] Using file descriptors

posted Nov 18, 2009 1:13 AM by Bruno Braga   [ updated Nov 18, 2009 1:27 AM ]
 
Working on a script for linscripts project (something I am working on my spare time), I encountered the following issue: I could not update a file info (such as a simple setting value) on a single line. I will explain in details:

I wanted to, by script, update a single value on a configuration file called apport, to enable crash reports on Ubuntu.
It is basically simple to do that such as:

    sed -e 's/enabled\=0/enabled\=1/' /etc/default/apport

However, the command below does not work:

    sed -e 's/enabled\=0/enabled\=1/' /etc/default/apport > /etc/default/apport

or worse, it removes all contents from the original file (do not try to do this!). So it means (I did not know) that stdin a file to a command and using the stdout directly does not work. Ok, you could do a temporary file and rename it back, of course, but I have found a more elegant solution in terms of scripting: to open a file for read/write using file descriptors:

# backup current file (always nice thing to do)
cp /etc/default/apport /etc/default/apport.old

# open the file for read/write into file descriptor 3
# (0, 1 and 2 are already taken by stdin, stdout and stderr respectively)
exec 3<> /etc/default/apport

# read the file, update and write it back
cat <&3 | sed -e 's/enabled\=0/enabled\=1/' >&3

# save/close
exec 3>&-

Nice!

References

    [1] http://tldp.org/LDP/abs/html/io-redirection.html

 BRAGA, Bruno

 



Brazilian currently based in Japan, working on Information Technology.