2

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

file

DEVICE0_USB="usbSerialNo1"
DEVICE1_USB="usbSerialNo2"

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

script

FAX_MACHINE_USB=$DEVICE0_USB
COFFEE_MAKER_USB=$DEVICE1_USB

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?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
pavel
  • 67

1 Answers1

4

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:

    variable="Hello"
    var2="Value2"
    

    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.