我尝试用git-bash将一个文件读入变量中。我用的是这样的东西:
readFile() {
local file="${1}"
local resultVar="${2}"
eval $resultVar="'$(cat ${file})'"
}类似于这里的建议,链接。
在大多数情况下,这是很好的。但是它可能会引起问题,这取决于文件中引号的数量。例如:
示例1❌
test1.txt:
text "quoted"code:
$ echo "text \"quoted\"" > test1.txt &&
> readFile "./test1.txt" test1 &&
> printf "test1: %s\n" "${test1}"
test1: text "quoted"ERROR:尾部\n的裁剪。
示例2❌
test2.txt:
text "one quotecode:
$ echo "text \"one quote" > test2.txt &&
> readFile "./test2.txt" test2 &&
> printf "test2: %s\n" "${test2}"
test2: text "one quoteERROR:尾部\n的裁剪。
示例3❌
test3.txt:
text 'quoted'code:
$ echo "text 'quoted'" > test3.txt &&
> readFile "./test3.txt" test3 &&
> printf "test3: %s\n" "${test3}"
test3: text quoted错误:这些single-quotes已被删除!
示例4❌
test4.txt:
text 'one quotecode:
$ echo "text 'one quote" > test4.txt &&
> readFile "./test4.txt" test4 &&
> printf "test4: %s\n" "${test4}"
bash: unexpected EOF while looking for matching `''
bash: syntax error: unexpected end of fileERROR:这会变得更糟.
示例5❌
test5.txt:
text 'quoted"code:
$ echo "text \'quoted\"" > test5.txt &&
> readFile "./test5.txt" test5 &&
> printf "test5: %s\n" "${test5}"
bash: unexpected EOF while looking for matching `"'
bash: syntax error: unexpected end of fileERROR:类似于上面的内容。
因此,如何在不知道文件包含的引号是否、多少和类型的情况下,将文件从函数中强劲地读取到变量中?
也许还有其他字符也能破解我的代码,但我没有检查。如果解决方案也能解决这些问题,那就太好了。
发布于 2020-12-16 14:47:33
这能实现你想要的吗?
#!/usr/bin/env bash
readFile() {
IFS= read -rd '' "$1" < "$2"
}
readFile var data-file
# Checking result
printf %s "$var" | xxd发布于 2020-12-16 08:00:46
不要使用eval。
在bash中,您可以使用$(<file)而不是$(cat file)。只是有点快。
您可以使用名称:
readFile() {
declare -n resultVar=$2
resultVar="$(<"$1")"
}如果没有零字节,可以使用readarray/mapfile。注意-它将保留尾随换行符,而不是删除尾随换行符的$(...):
readFile() {
readarray -d '' -t "$2" < "$1"
}如果您真的想使用eval,那么使用declare
readFile() {
declare -g "$2=$(< "$1")"
}如果您真的想使用eval,请始终将一个正确的转义字符串传递给它。总是在printf "%q"之后
readFile() {
eval "$(printf "%q" "$2")=$(printf "%q" "$(< "$1")")"
}https://stackoverflow.com/questions/65319194
复制相似问题