将 bash 变量设置为等于字符串的结果,其中换行符被空格替换
Set bash variable equal to result of string where newlines are replaced by spaces
我有一个等于字符串的变量,它是由换行符分隔的一系列 key/value 对。
然后我想用空格替换这些换行符,并设置一个等于结果的新变量
根据互联网上的各种答案,我得出以下结论:
#test.txt has the content:
#test=example
#what=s0omething
vars="$(cat ./test.txt)"
formattedVars= $("$vars" | tr '\n' ' ')
echo "$taliskerEnvVars"
问题是当我尝试设置 formattedVars
它试图执行第二行:
script.sh: line 7: test=example
what=s0omething: command not found
我只想让formattedVars
等于test=example what=s0omething
我错过了什么技巧?
将您的线路更改为:
formattedVars=$(tr '\n' ' ' <<< "$secretsContent")
请注意代码中 =
的 space,这在赋值语句中是不允许的。
我看到您没有在代码中设置 secretsContent
,而是设置了 vars
。
如果可能,使用数组来保存文件的内容:
readarray -t vars < ./test.txt # bash 4
或
# bash 3.x
declare -a vars
while IFS= read -r line; do
vars+=( "$line" )
done < ./test.txt
然后你就可以用数组做你想做的事了。您可以使用
制作 space 分隔的列表
formattedVars="${vars[*]}"
,但考虑是否需要。如果目标是将它们用作前置命令修饰符,请使用,例如,
"${vars[@]}" my_command arg1 arg2
我有一个等于字符串的变量,它是由换行符分隔的一系列 key/value 对。
然后我想用空格替换这些换行符,并设置一个等于结果的新变量
根据互联网上的各种答案,我得出以下结论:
#test.txt has the content:
#test=example
#what=s0omething
vars="$(cat ./test.txt)"
formattedVars= $("$vars" | tr '\n' ' ')
echo "$taliskerEnvVars"
问题是当我尝试设置 formattedVars
它试图执行第二行:
script.sh: line 7: test=example
what=s0omething: command not found
我只想让formattedVars
等于test=example what=s0omething
我错过了什么技巧?
将您的线路更改为:
formattedVars=$(tr '\n' ' ' <<< "$secretsContent")
请注意代码中 =
的 space,这在赋值语句中是不允许的。
我看到您没有在代码中设置 secretsContent
,而是设置了 vars
。
如果可能,使用数组来保存文件的内容:
readarray -t vars < ./test.txt # bash 4
或
# bash 3.x
declare -a vars
while IFS= read -r line; do
vars+=( "$line" )
done < ./test.txt
然后你就可以用数组做你想做的事了。您可以使用
制作 space 分隔的列表formattedVars="${vars[*]}"
,但考虑是否需要。如果目标是将它们用作前置命令修饰符,请使用,例如,
"${vars[@]}" my_command arg1 arg2