0

I have a folder named MyProperties and it contains multiple .properties files like 1.properties, 2.properties, 3.properties and so on. Each file has contains something like:

keyname=value 

What should I write here as the value in the properties file so that it gets assigned or replaced? How do I iterate over these in a bash script and assign the value to the key?

Pseudo code:

#!/bin/bash
valuetobepassed="something"
#iterate over each file in the folder and replace/assign value corresponding to keyname
ilkkachu
  • 138,973
HDev007
  • 261
  • If you want the properties available to the shell, but don't want them on the main level (where they could trash HOME or PATH), and don't need or want to support the full shell syntax, you could arrange to read them to an associative array... – ilkkachu Apr 25 '17 at 12:29

2 Answers2

1

If you really have multiple files with varName=value pairs, then all you need to do is source it. So, iterate over all .properties files and source each of them :

for file in /path/to/MyProperties/*.properties; do
    . "$file"
done

You now have all your variables defined in your script. To illustrate:

$ cat foo.properties 
foo="bar"
$ echo "$foo"  ## no value

$ . ./foo.properties 
$ echo "$foo"
bar

This assumes your .properties files have nothing but variable=value pairs. When sourcing, each line of the file will be executed in the shell running the script doing the sourcing. So, any commands in your .properties files will also be executed. And any attacker with access to MyProperties can add a malicious command there. So only do this if you can be certain of the files' contents.

Note that it's important that the path given to the . builtin contains a / character (hence the ./foo.properties above) as otherwise the file is looked up in the directories of $PATH instead of the current directory (in the case of bash and when not in POSIX compliance mode, . file looks for file in the current working directory if it has not been found in $PATH).

terdon
  • 242,166
1

You can use sed to replace values in files:

#!/bin/bash

new_value=5
for f_name in MyProperties/*.properties; do
     sed -i "s/^keyname=.*$/keyname=$new_value/" "$f_name"
done
terdon
  • 242,166
VBM
  • 11
  • 2