首页 > 解决方案 > 在 Shell 脚本中连接字符串和变量

问题描述

文件内容为:

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

外壳脚本:

#!/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

预期输出:

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

输出:

每次都有一些意想不到的 o/p

前任。-lp 7890rogram.jar

看起来它一次又一次地覆盖同一行

标签: bashshellstring-concatenation

解决方案


关于给出的注释并在脚本中进行额外的自动数据清理,您可以根据如何在 Bash 脚本中将 DOS/Windows 换行符 (CRLF) 转换为 Unix 换行符 (LF)?删除 Unix 中的回车符

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

在您的脚本中。这将防止在以后的运行中出错。


推荐阅读