[英]How do I read a file into a variable with an unknown number of quotes in Bash
我嘗試使用git-bash
將文件讀入變量。 我正在使用這樣的東西:
readFile() {
local file="${1}"
local resultVar="${2}"
eval $resultVar="'$(cat ${file})'"
}
類似於此處建議的Link 。
這在大多數情況下都可以正常工作。 但它可能會導致問題,具體取決於文件中的引號數量。 例如:
test1.txt
:
text "quoted"
code
:
$ echo "text \"quoted\"" > test1.txt && > readFile "./test1.txt" test1 && > printf "test1: %s\n" "${test1}" test1: text "quoted"
錯誤:末尾的尾隨\n
的剪切。
test2.txt
:
text "one quote
code
:
text 'quoted'
錯誤:末尾的尾隨\n
的剪切。
test3.txt
:
text 'quoted'
code
:
$ 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 file
錯誤:這些single-quotes
已被刪除!
test4.txt
:
text 'one quote
code
:
$ 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 file
錯誤:這變得更糟......
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 file
錯誤:與上述類似。
那么,如何在不知道它是否包含引號、包含多少引號以及包含什么類型的引號的情況下,將 function 中的文件穩健地讀取到變量中?
也許還有其他字符也可能破壞我的代碼,但我沒有檢查。 如果解決方案也能解決這些問題,那就太好了。
不要使用評估。
在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")")"
}
這能達到你想要的嗎?
#!/usr/bin/env bash
readFile() {
IFS= read -rd '' "$1" < "$2"
}
readFile var data-file
# Checking result
printf %s "$var" | xxd
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.