Can we assign to any file a file descriptor number actually?
Yes you can. But it is up to the program in question if it does something with it.
$ cat fd.c
int main()
{
write(5,"test\n",5);
}
$ gcc fd.c
$ ./a.out 5> file
$ cat file
test
$ ./a.out 5>&1
test
$ ./a.out
$
In that last case, the output to fd 5 vanished.
openssl
uses this to allow passphrases and such to be passed to the process without using regular argv
(which may expose them).
update the input case:
$ cat fd_in.c
int main()
{
unsigned char buf[16];
write(5,buf,read(6,buf,16));
}
$ gcc fd_in.c
$ ./a.out 6< file 5>&1
test
(file
contained test\n
from the previous example)
Yes, in bash you can use file descriptor
for reading and/or writing and can use any number. However, since 0, 1 and 2 is used for STDIN, STDOUT and STDERR, we avoid those. Also, numbers greater than 9 are used internally so we tend to avoid those as well.
This is how we can open a file descriptor to do the following:
fd<source
fd>source
fd<>source
where fd
is a digit that describes file descriptor
and source
can be either a file
or even another file descriptor
(though you would add &
before it).
If you are using exec
for file descriptors then that allows the changes to take effect in the current shell. Otherwise they are local to function or loop.
Following use of fd will be local to while loop and you cannot use it outside:
while read line <&3; do
echo $line;
done 3<test.file
Following use of fd will be visible in the current shell
exec 3<test.file
while read line <&3; do
echo $line;
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With