help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] too paranoid?


From: Stephane Chazelas
Subject: Re: [Help-bash] too paranoid?
Date: Thu, 10 Mar 2016 17:05:06 +0000
User-agent: Mutt/1.5.21 (2010-09-15)

2016-03-10 09:43:48 -0600, John McKown:
[...]
> temp1='/dev/fd/10' #and now use it nicely
> #
> # repeat above for temp2, using /dev/fd/12, and so on
> process input-file.txt >${temp1}
> process input-file2 >${temp2}
> cat ${temp2} ${temp1} ${temp3} >./result-file.txt
> 
> Basically, I am making sure that my temporary files are unlinked almost
> immediately after they have been created, but am able to access the data
> due to the "exec ??>" opening the inode, via the name, and accessing it
> using the /dev/fd/??
> 
> Is this going to fail on me, in UNIX, some day? Or is there some problem
> which might come up by doing this?
[...]

The above will only work on Linux, not in other Unices.

On Linux, opening /dev/fd/10 when fd 10 points to a regular file
will open the file anew. In other Unices that support /dev/fd/n,
opening /dev/fd/10 will be more like a dup(10), so the new fd
will share the same open file description and in particular the
same opening mode (read, write) and position within the file.

Since you're using bash (though it would work with zsh and some
implementations of ksh), you can use process substitution:

cat <(cmd1) <(cmd2) <(cmd3) > result-file.txt

(that uses pipes instead of temp files)

Though here, if it's just for cat, you can of course do:
(cmd1; cmd2; cmd3) > result-file.txt

If you need back-up files and want to both read an write to it,
and that to work on non-Linux systems, you'd need either to open
the file on two fds:

exec 3> "$file" 4< "$file"
rm -- "$file"

cmd1 >&3
cat /dev/fd/4

And if you need to read the file a second time, you'd need yet
another fd.

Or you can use a shell that can fseek file descriptors like
ksh93 or zsh, and you could then use a file descriptor open in
read+write. With ksh93:

exec 3<> "$file"
rm -- "$file"

cmd1 >&3
exec 3>#((0)) # seek back to beginning.

cat /dev/fd/3 ...

-- 
Stephane




reply via email to

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