I want to read the file and assign the values to variables whic is in another file using shell script.

For example I have file as "myconf"


and my script in another file as "testconf"

$cli -u $user -p $passwd -s $host -f $file3 > $file4

I want to get the values for the variables(cli,user etc) from "myconf" file. Used while loop to read the values it has been assigning the entire line (cli="/opt/Solartis_Monitoring/JON_CLI/bin/rhq-cli.sh") to $cli. Need to assign only the values after the field separator(=) to my variable


echo $cli should print /opt/Solartis_Monitoring/JON_CLI/bin/rhq-cli.sh not as cli="/opt/Solartis_Monitoring/JON_CLI/bin/rhq-cli.sh"

I cant change "myconf" file it is predefined one. Please help on this

1 Answer 1


The Careful Approach


while IFS== read -r var value
    [ "$var" ] && declare "$var=${value%\"}"
done <myconf
echo "$cli"

This produces the output:


How it works

  • while IFS== read -r var value; do

    This starts a loop. It temporarily sets the field separator, IFS, to an equal sign, =. It then reads a line and separates the line into the two variables var and value. var gets assigned to whatever is before the first = and value gets whatever is after the first =.

  • value="${value#\"}"

    This removes the leading " from the value.

  • [ "$var" ] && declare "$var=${value%\"}"

    If var is not empty, in other words, if we have not read an empty line, then assign the variable $var to the value ${value%\"}" where ${value%\"}" removes the trailing " from $value.

  • done <myconf

    This signals the end of the loop and sets the loops input from the file myconf.

The Trusting Approach

This sources the file myconf:

. myconf
echo "$cli"

This produces the output:


Because this approach executes the file myconf, it requires you to trust whoever created myconf. If the file myconf contains any shell-active characters, the results might not be what you want.

  • The idea of setting IFS to = is interesting. I take it setting IFS to = leaves the line/record separator of \n untouched, in other words read will still read only a single line a time, another while loop will happen, then read does another single line etc etc? Jun 30, 2016 at 6:39
  • @the_velour_fog Yes, that is right. Unless the -d option is set, read will read exactly one line at a time. IFS only affects how word splitting is performed on that line.
    – John1024
    Jun 30, 2016 at 7:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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