从 Bash 中的 Here Document 读取多行变量的完美方法是什么?
看看我的做法是如何产生返回的1
副作用$?
......
巴什代码:
#!/bin/bash
printf "Unsetting...\n"
unset variable
printf "Exit status: %s.\n" "$?"
printf "Variable: %s.\n" "${variable}"
printf "\n"
printf "Setting to 'foo'...\n"
variable='foo'
printf "Exit status: %s.\n" "$?"
printf "Variable: %s.\n" "${variable}"
printf "\n"
printf "Setting to 'bar' by reading stdin from process substitution...\n"
read variable < <(echo 'bar')
printf "Exit status: %s.\n" "$?"
printf "Variable: %s.\n" "${variable}"
printf "\n"
printf "Setting to 'baz' by reading stdin from Here String...\n"
here_string='baz'
read variable <<< "${here_string}"
printf "Exit status: %s.\n" "$?"
printf "Variable: %s.\n" "${variable}"
printf "\n"
printf "Setting to 'quux' by reading stdin from Here Document...\n"
read variable <<- 'EOF'
quux
EOF
printf "Exit status: %s.\n" "$?"
printf "Variable: %s.\n" "${variable}"
printf "\n"
printf "Setting to 'thud <newline> thud' by reading stdin from Here Document...\n"
read -d '' variable <<- 'EOF'
thud
thud
EOF
printf "Exit status: %s.\n" "$?" # ONE?!one!!oneone? :)
printf "Variable: %s.\n" "${variable}"
输出
Unsetting...
Exit status: 0.
Variable: .
Setting to 'foo'...
Exit status: 0.
Variable: foo.
Setting to 'bar' by reading stdin from process substitution...
Exit status: 0.
Variable: bar.
Setting to 'baz' by reading stdin from Here String...
Exit status: 0.
Variable: baz.
Setting to 'quux' by reading stdin from Here Document...
Exit status: 0.
Variable: quux.
Setting to 'thud <newline> thud' by reading stdin from Here
Document...
Exit status: 1.
Variable: thud
thud.