Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading variables from a text file into bash script

Tags:

bash

Is it possible to load new lines from a text file to variables in bash?

Text file looks like?

EXAMPLEfoo 
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

Variables become

$1 = EXAMPLEfoo 
$2 = EXAMPLEbar 

ans so on?

like image 264
S1syphus Avatar asked Apr 16 '10 12:04

S1syphus


2 Answers

cat somefile.txt| xargs bash_command.sh

bash_command.sh will receive these lines as arguments

like image 43
Андрей Костенко Avatar answered Sep 21 '22 08:09

Андрей Костенко


$ s=$(<file)
$ set -- $s
$ echo $1
EXAMPLEfoo
$ echo $2
EXAMPLEbar
$ echo $@
EXAMPLEfoo EXAMPLEbar EXAMPLE1 EXAMPLE2 EXAMPLE3 EXAMPLE4

I would improve the above by getting rid of temporary variable s:

$ set -- $(<file)

And if you have as input a file like this

variable1 = value
variable2 = value

You can use following construct to get named variables.

input=`cat filename|grep -v "^#"|grep "\c"`
set -- $input

while [ $1 ]
 do
  eval $1=$3
  shift 3
 done
like image 112
ghostdog74 Avatar answered Sep 20 '22 08:09

ghostdog74