file descriptor - exec vs inline
Hi,
What's the difference between using file descriptors (fd) with & without exec? Example: This reads a single line on fd 5 from file f: Code:
read -u5 i 5<f With exec (fd opened & closed manually): Code:
exec 5<f ; read -u5 i ; exec 5<&- Thanks |
Code:
read -u5 i 5<f Code:
exec 5<f But you know it already. |
Thanks :thumbsup:
So in the example I've given fd 5 will auto-closed after the read command finishes?. |
Quote:
|
Code:
read -u5 i 5<f No need for the extra descriptor here. Code:
read i <f The exec lets the shell permanently open the file. Until it's closed with another exec. Code:
exec 5<f But I prefer a code block in favor of an exec/exec. Code:
{ If the block is very long, I usually put a comment at the beginning: Code:
# &5 is from file f Code:
{ |
Quote:
Quote:
Code:
exec {FD}<f https://tldp.org/LDP/abs/html/io-redirection.html |
My needs in these things are always modest, but I do enjoy the discussions. Thanks to all.
|
Only the exec overwrites a previous file descriptor!
A redirected command sets a file descriptor in a new context: Code:
exec 5< /etc/nsswitch.conf Regarding the redirected code block, it opens a new descriptor context but not a new shell scope (no fork). Example with nested code blocks: Code:
exec 5< /etc/nsswitch.conf A modern shell avoids a sub shell, unless you enforce it by using ( ) instead of { } But a pipe from/to a code block still enforces a sub shell. Code:
echo hello | while read i; do echo "Sub shell: i=$i"; done BTW even for-do-done if-then-fi case-esac are code blocks. For ex you can do Code:
if [ "$1" = "head" ] |
All times are GMT -5. The time now is 01:23 AM. |