Reputation: 46
I am trying to create multiple descriptors to files named 1, 2, 3, etc. in bash.
For example, exec 9>abc/1
works just fine, but when I try to create descriptors in a for loop, like this: exec $[$i+8]>abc/$i
, it doesn't work. I tried many different ways, but it seems that exec
just does not accept variables. Is there any way to do what I want to?
EDIT: If not, maybe there is a way to use flock
without descriptors?
Upvotes: 1
Views: 802
Reputation: 6657
Yes, exec
doesn't accept variables for file descriptor numbers. As pointed out in comments, you can use
eval "exec $((i + 8))>"'"abc/$i"'
which, if $i
is 1
, is equivalent to
exec 9>"abc/$i"
Those complex quotes ensure that eval-ed and then exec-ed command is safe even if file name is changed to something different than abc/1
.
But there is a warning:
Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally.
So if your task doesn't require consecutive file descriptor numbers, you can use automatically allocated descriptors:
Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form
{varname}
. In this case, for each redirection operator except>&-
and<&-
, the shell will allocate a file descriptor greater than 10 and assign it tovarname
.
So,
exec {fd}>"abc/$i"
echo "$fd"
will open file descriptor 10 (or greater) for writing to abc/1
and print that file descriptor number (e.g. 10
).
Upvotes: 1