Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one store a variable in a file using bash?

Tags:

bash

I can redirect the output and then cat the file and grep/awk the variable, but I would like to use this file for multiple variables.

So If it was one variable say STATUS then i could do some thing like

echo "STATUS $STATUS" >> variable.file
#later perhaps in a remote shell where varible.file was copied
NEW_VAR=`cat variable.file | awk print '{$2}'`

I guess some inline editing with sed would help. The smaller the code the better.

like image 465
geoaxis Avatar asked May 11 '11 14:05

geoaxis


People also ask

How do you store a variable in a file?

You can use the variable operation command. You can use the command read from text file and move the data into the variable. Also, you can read from txt file using a system variable and then store it to different variable using Variable operation command.

How do you store a variable in shell?

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 ...]


2 Answers

One common way of storing variables in a file is to just store NAME=value lines in the file, and then just source that in to the shell you want to pick up the variables.

echo 'STATUS="'"$STATUS"'"' >> variable.file
# later
. variable.file

In Bash, you can also use source instead of ., though this may not be portable to other shells. Note carefully the exact sequence of quotes necessary to get the correct double quotes printed out in the file.

If you want to put multiple variables at once into the file, you could do the following. Apologies for the quoting contortions that this takes to do properly and portably; if you restrict yourself to Bash, you can use $"" to make the quoting a little simpler:

for var in STATUS FOO BAR
do
    echo "$var="'"'"$(eval echo '$'"$var")"'"'
done >> variable.file
like image 135
Brian Campbell Avatar answered Sep 19 '22 21:09

Brian Campbell


The declare builtin is useful here

for var in STATUS FOO BAR; do
    declare -p $var | cut -d ' ' -f 3- >> filename
done

As Brian says, later you can source filename

declare is great because it handles quoting for you:

$ FOO='"I'"'"'m here," she said.'
$ declare -p FOO
declare -- FOO="\"I'm here,\" she said."
$ declare -p FOO | cut -d " " -f 3-
FOO="\"I'm here,\" she said."
like image 31
glenn jackman Avatar answered Sep 21 '22 21:09

glenn jackman