How to save a variable in a file using bash?

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

So, if one variable said STATUS, then I could do something 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 think some inline editing with sed will help. The smaller the code, the better.

+4
source share
2 answers

Here's the built-in declare

 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 excellent 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." 
+8
source

One common way to store variables in a file is to simply save the NAME=value lines in the file, and then simply indicate that you want the variables to be wrapped.

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

In Bash, you can also use source instead . although this may not be tolerable for other shells. Pay attention to the exact sequence of quotes needed to get the correct double quotes printed in the file.

If you want to put several variables into a file at once, you can do the following. Sorry for the quotation required for proper and portable work; if you're limiting yourself to bash, you can use $"" to make the quote a little easier:

 for var in STATUS FOO BAR do echo "$var="'"'"$(eval echo '$'"$var")"'"' done >> variable.file 
+6
source

All Articles