Marcos Griselli
Marcos Griselli

Reputation: 1346

Read a Bash variable assignment from other file

I have this test script:

#!/bin/bash
echo "Read a variable" 
#open file
exec 6<test.txt
read EXAMPLE <&6
#close file again
exec 6<&-
echo $EXAMPLE

The file test.txt has only one line:

EXAMPLE=1

The output is:

bash-3.2$ ./Read_Variables.sh
Read the variable
EXAMPLE=1

I need just to use the value of $EXAMPLE, in this case 1. So how can I avoid getting the EXAMPLE= part in the output?

Thanks

Upvotes: 3

Views: 9796

Answers (4)

chepner
chepner

Reputation: 530862

As an alternative to sourcing the entire file, you can try the following:

while read line; do
    [[ $line =~ EXAMPLE= ]] && declare "$line" && break
done < test.txt

which will scan the file until it finds the first line that looks like an assignment to EXAMPLE, then use the declare builtin to perform the assignment. It's probably a little slower, but it's more selective about what is actually executed.

Upvotes: 7

Michał Trybus
Michał Trybus

Reputation: 11784

I think the most proper way to do this is by sourcing the file which contains the variable (if it has bash syntax), but if I were to do that, I'd source it in a subshell, so that if there are ever other variables declared there, they won't override any important variables in current shell:

(. test.txt && echo $EXAMPLE)

Upvotes: 5

user1019830
user1019830

Reputation:

You could read the line in as an array (notice the -a option) which can then be indexed into:

# ...
IFS='=' read -a EXAMPLE <&6
echo ${EXAMPLE[0]} # EXAMPLE
echo ${EXAMPLE[1]} # 1
# ...

This call to read splits the input line on the IFS and puts the remaining parts into an indexed array. See help read for more information about read options and behaviour. You could also manipulate the EXAMPLE variable directly:

# ...
read EXAMPLE <&6
echo ${EXAMPLE##*=} # 1
# ...

If all you need is to "import" other Bash declarations from a file you should just use:

source file  

Upvotes: 0

Joe Holloway
Joe Holloway

Reputation: 28948

If the file containing your variables is using bash syntax throughout (e.g. X=Y), another option is to use source:

#!/bin/bash
echo "Read a variable" 
source test.txt
echo $EXAMPLE

Upvotes: 9

Related Questions