Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file into a variable in shell?

Tags:

shell

unix

sh

I want to read a file and save it in variable, but I need to keep the variable and not just print out the file. How can I do this? I have written this script but it isn't quite what I needed:

#!/bin/sh while read LINE   do     echo $LINE   done <$1   echo 11111-----------   echo $LINE   

In my script, I can give the file name as a parameter, so, if the file contains "aaaa", for example, it would print out this:

aaaa 11111----- 

But this just prints out the file onto the screen, and I want to save it into a variable! Is there an easy way to do this?

like image 497
kaka Avatar asked Sep 15 '11 07:09

kaka


People also ask

How do you read a variable from a file in Linux?

To read variables from a file we can use the source or . command. One reason why you might not want to do it this way is because whatever is in <filename> will be run in your shell, such as rm -rf / , which could be very dangerous. OTOH, it is the answer to the question I asked google and google brought me here.

How do I read a file in a bash script?

Syntax: Read file line by line on a Bash Unix & Linux shell The syntax is as follows for bash, ksh, zsh, and all other shells to read a file line by line: while read -r line; do COMMAND; done < input. file. The -r option passed to read command prevents backslash escapes from being interpreted.


2 Answers

In cross-platform, lowest-common-denominator sh you use:

#!/bin/sh value=`cat config.txt` echo "$value" 

In bash or zsh, to read a whole file into a variable without invoking cat:

#!/bin/bash value=$(<config.txt) echo "$value" 

Invoking cat in bash or zsh to slurp a file would be considered a Useless Use of Cat.

Note that it is not necessary to quote the command substitution to preserve newlines.

See: Bash Hacker's Wiki - Command substitution - Specialities.

like image 139
Alan Gutierrez Avatar answered Sep 17 '22 13:09

Alan Gutierrez


If you want to read the whole file into a variable:

#!/bin/bash value=`cat sources.xml` echo $value 

If you want to read it line-by-line:

while read line; do         echo $line     done < file.txt 
like image 29
brain Avatar answered Sep 17 '22 13:09

brain