Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a file and redirect it to a variable?

I have a file with a word written on it. I want my script to put that word in a variable.

How can I do that?

like image 865
The Student Avatar asked Jan 20 '11 16:01

The Student


People also ask

How do you redirect output to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...] arg1 arg2 ...'

How do you store a file in a variable in Linux?

One way we can write variable contents to a file is to use the echo command along with the redirect operator. In this case, the -e argument applies to the call to echo and is not sent as output to the file. So we only see “some value”.


1 Answers

in several of a million ways...

simplest is probably

my_var=$(cat my_file) 

If you use bash and you want to get spiffy you can use bash4's mapfile, which puts an entire file into an array variable, one line per cell

mapfile my_var < my_file 
like image 169
wich Avatar answered Sep 22 '22 12:09

wich