Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a variable to indicate a file descriptor in bash?

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?

like image 953
WH's HeV Avatar asked Nov 28 '11 12:11

WH's HeV


People also ask

What does $_ mean in bash?

$_ (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.

How do you use variables in bash commands?

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.

How do you set a variable value in bash?

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.


2 Answers

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 
like image 97
Paul Tobias Avatar answered Oct 01 '22 03:10

Paul Tobias


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.

like image 29
eduffy Avatar answered Oct 01 '22 01:10

eduffy