29

I have a file like

name1=value1
name2=value2

I need to read this file using shell script and set variables

$name1=value1
$name2=value2

Please provide a script that can do this.

I tried the first answer below, i.e. sourcing the properties file but I'm getting a problem if the value contains spaces. It gets interpreted as a new command after the space. How can I get it to work in the presence of spaces?

Martin Schröder
  • 3,546
  • 5
  • 43
  • 77
Hugh Darling
  • 1,709
  • 7
  • 29
  • 46
  • Related: https://stackoverflow.com/questions/15365871/code-for-parsing-a-key-value-in-in-file-from-shell-script – tripleee Oct 10 '17 at 09:37

8 Answers8

30

If all lines in the input file are of this format, then simply sourcing it will set the variables:

source nameOfFileWithKeyValuePairs

or

. nameOfFileWithKeyValuePairs
Joachim Sauer
  • 291,719
  • 55
  • 540
  • 600
  • 1
    Hey, I'm getting problem if the value contains spaces. It gets interpreted as a new command after the space. Please tell how to get it working in the presence of spaces. – Hugh Darling Feb 15 '11 at 11:35
  • 2
    I have dots in my keys (e.g. `data.dir=/path/to/data/dir`). It gives errors such as `Command not found` or `No such file or directory` depending on the value. Any idea how to fix this issue? – Isaac Sep 06 '13 at 23:33
  • As noted elsewhere here, 'source' works for many cases but a) may have security implications, and b) will not function for values that have for example "$" in them. – NuSkooler Sep 19 '18 at 18:34
  • Why you should not source file (big security risk) - https://unix.stackexchange.com/a/433245/364638 – Shishir Gupta Jun 16 '21 at 07:56
17

Use:

while read -r line; do declare  "$line"; done <file
codesalsa
  • 794
  • 4
  • 18
kurumi
  • 24,217
  • 4
  • 43
  • 49
16

Sourcing the file using . or source has the problem that you can also put commands in there that are executed. If the input is not absolutely trusted, that's a problem (hello rm -rf /).

You can use read to read key value pairs like this if there's only a limited known amount of keys:

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      "name1") name1="$value" ;;
      "name2") name2="$value" ;;
    esac
  done < "$file"
}
robinst
  • 28,003
  • 9
  • 98
  • 103
13

if your file location is /location/to/file and the key is mykey:

grep mykey $"/location/to/file" | awk -F= '{print $2}'
consuela
  • 1,667
  • 6
  • 23
  • 24
Alex Stoliar
  • 165
  • 2
  • 8
7

Improved version of @robinst

read_properties()
{
  file="$1"
  while IFS="=" read -r key value; do
    case "$key" in
      '#'*) ;;
      *)
        eval "$key=\"$value\""
    esac
  done < "$file"
}

Changes:

  • Dynamic key mapping instead of static
  • Supports (skips) comment lines

A nice one is also the solution of @kurumi, but it isn't supported in busybox

And here a completely different variant:

eval "`sed -r -e "s/'/'\\"'\\"'/g" -e "s/^(.+)=(.+)\$/\1='\2'/" $filename`"

(i tried to do best with escaping, but I'm not sure if that's enough)

Daniel Alder
  • 4,632
  • 2
  • 46
  • 50
  • 1
    This is a good one, but it does not read the last line. How to fix? – Andrew Apr 03 '20 at 02:32
  • @Andrew good point, didn't know about this. Seems to be something in `read -r key value` which I cannot even reproduce without the loop. Any help out there? – Daniel Alder Apr 03 '20 at 13:14
6

suppose the name of your file is some.properties

#!/bin/sh
# Sample shell script to read and act on properties

# source the properties:
. some.properties

# Then reference then:
echo "name1 is $name1 and name2 is $name2"
Clyde Lobo
  • 9,033
  • 7
  • 35
  • 61
  • 3
    While true, this should come with the big blinking red warning label that reads "EVAL! EVAL! YOU'RE USING EVAL HERE!" unless there is absolute undoubted control over the input file. – Ulrich Schwarz Feb 14 '11 at 09:47
  • Is there any difference if I source as .some.properties and . ./some.properties – Bharthan Jul 19 '16 at 16:38
0

Use shdotenv

dotenv support for shell and POSIX-compliant .env syntax specification https://github.com/ko1nksm/shdotenv

Usage: shdotenv [OPTION]... [--] [COMMAND [ARG]...]

  -d, --dialect DIALECT  Specify the .env dialect [default: posix]
                           (posix, ruby, node, python, php, go, rust, docker)
  -s, --shell SHELL      Output in the specified shell format [default: posix]
                           (posix, fish)
  -e, --env ENV_PATH     Location of the .env file [default: .env]
                           Multiple -e options are allowed
  -o, --overload         Overload predefined environment variables
  -n, --noexport         Do not export keys without export prefix
  -g, --grep PATTERN     Output only those that match the regexp pattern
  -k, --keyonly          Output only variable names
  -q, --quiet            Suppress all output
  -v, --version          Show the version and exit
  -h, --help             Show this message and exit

Load the .env file into your shell script.

eval "$(shdotenv [OPTION]...)"
-6

sed 's/^/\$/' yourfilename

Yrgl
  • 621
  • 1
  • 5
  • 17