0

Content of file is:

#data.conf
ip=127.0.0.1
port=7890
delay=10
key=1.2.3.4
debug=true

Shell Script:

#!/bin/bash
typeset -A config
config=()
config_file_path="./data.conf"
cmd="java -jar ./myprogram.jar"

#This section will read file and put content in config variable
while read line
do
    #echo "$line"
    if echo $line | grep -F = &>/dev/null
    then
        key=$(echo "$line" | cut -d '=' -f 1)
        config[$key]=$(echo "$line" | cut -d '=' -f 2)
        echo "$key" "${config["$key"]}"
    fi
done < "$config_file_path"

cmd="$cmd -lh ${config["ip"]} -lp ${config["port"]} -u ${config["debug"]} -hah \"${config["key"]}\" -hap ${config["delay"]}"
echo $cmd

Expected output:

java -jar myprogram.jar -lh 127.0.0.1 -lp 7890 -u true -hah "1.2.3.4" -hap 10 -b

Output:

Every time some unexpected o/p

Ex. -lp 7890rogram.jar

Looks like it is overwriting same line again and again

Community
  • 1
  • 1
Shivam Seth
  • 677
  • 1
  • 8
  • 21
  • `config[$key]=` Should be `config[$key]+=` If you want to add element to array – Digvijay S May 05 '20 at 03:49
  • IMHO, if you could post sample of your input file I am pretty sure we may do it better way too. – RavinderSingh13 May 05 '20 at 04:04
  • 4
    At least one of your files, probably data.conf (and *maybe* the script) has DOS/Windows line endings, and that's confusing things. See: [Are shell scripts sensitive to encoding and line endings?](https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings) – Gordon Davisson May 05 '20 at 04:08
  • 1
    Thanks @Gordon, this was definitely an issue – Shivam Seth May 05 '20 at 05:16

1 Answers1

0

In respect to the comments given and to have an additional automatic data cleansing within the script, you could have according How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script? and Remove carriage return in Unix

# This section will clean the input config file
sed -i 's/\r$//' "${config_file_path}"

within your script. This will prevent the error in future runs.

U880D
  • 8,601
  • 6
  • 24
  • 40