I have a file with a bunch of variables such as:



and I want to assign the contents of any of these variables to variables in a script, for instance:



so that when I echo $FAX_MACHINE_USB I receive usbSerialNo1

I can use source to get the variables from file but this will also run every line in file. In my case it's not a problem since file has only variable declarations, but I still prefer not to do it. Is there another way of achieving it?

marked as duplicate by Arkadiusz Drabczyk, Philippos, Rui F Ribeiro, xhienne, Jeff Schaller Aug 25 '17 at 19:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    The common practice is to source it. Why do you not want to do so? – Duncan X Simpson Aug 25 '17 at 15:51
  • You can use file to replace the variables in script without executing file following this question and answer – Philippos Aug 25 '17 at 16:21
  • 1
    Quote your variables when you use them. So FAX_MACHINE_USB="$DEVICE0_USB". – roaima Aug 25 '17 at 18:22

It seems a similar question was answered here.

You can of course use . or source to assign the variables if you are comfortable, but you can also use awk or grep to only run specific lines from the file that look like variable declerations.

How to handle many variables

If you want to source all the variables assigned in script1.sh, consider:

source <(grep -E '^\w+=' script1.sh)

This uses grep to extract all lines from script1.sh that look like variable assignments. These lines are then run in the current shell, assigning the variables.

If you use this approach first check to make sure that you want all the variables and that there aren't any that will interfere with what you are doing. If there are such, we can exclude them with a second grep command.

Considering the pieces in turn:

  • source file tells the shell to execute the file in the current shell.

  • <(...) is called process substitution. It allows us to use the output of a command in place of a file name.

  • The command grep -E '^\w+=' script1.sh extracts all lines that seem like variable assignments. If you run this command by itself on the command line, you should see something like:


    and so on. You should do this first and inspect the output to make sure that these are the lines that you want to execute.

Not the answer you're looking for? Browse other questions tagged or ask your own question.