I want to use a bash variable to indicate a file descriptor, like this:
id=6 file=a exec $id<>$file
But the usage is wrong:
-bash: exec: 6: not found
So, how to use a variable to indicate a file descriptor in exec command?
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Using variable from command line or terminal You don't have to use any special character before the variable name at the time of setting value in BASH like other programming languages. But you have to use '$' symbol before the variable name when you want to read data from the variable.
To create a variable, you just provide a name and value for it. Your variable names should be descriptive and remind you of the value they hold. A variable name cannot start with a number, nor can it contain spaces. It can, however, start with an underscore.
The accepted answer is correct, but as of bash 4.1, you can use automatic file descriptor allocation, and in that case you don't need eval
:
file=a exec {id}<>"$file"
Then you can use it like this:
echo test >&${id}
or:
fsck -v -f -C ${id} /dev/something
You have to use eval
and put the entire expression in quotes.
eval "exec $id<>$file"
And do that every time you want to use $id
.
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