我已经写了一个查询:
function print_ui_hosts
{
local sql = "select ........."
print_sql "$ sql"
}
本地 SQL - 一个非常长的字符串。查询未格式化。 如何将一个字符串拆分成多行?
只需在必要的地方插入新行。
sql="
SELECT c1, c2
from Table1, Table2
where ...
"
Shell 会寻找闭合引号。
sql="SELECT c2, c2
开始。 - bhfailor使用以下示例中显示的heredoc与read
一起使用:
read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF
echo "$sql"
read
命令的退出码是1;如果这很重要(例如,您正在使用set -e
运行),则需要在第一行末尾添加|| true
。 - chepnerset -e
将退出 shell。所谓“未预料”是指在不特别关注其退出状态的情况下运行。例如,单独使用 false
命令会导致 shell 退出。但是,在 false || true
中,由于您通过指定另一个要运行的命令来反应第一个命令失败的情况,因此不会退出。 - chepner-d ' '
是什么意思? - hg_gitread
函数在遇到换行符时不要停止读取。 - Cyker在大多数情况下,其他回答已经足够了,但我想再提供一个额外的答案。
我想将一个字符串分成多行编写,但其内容需要是单行。
sql=" \
SELECT c1, c2 \
from Table1, ${TABLE2} \
where ... \
"
如果这样说有点离题的话,我很抱歉(因为我不需要这个针对SQL)。但是,在搜索多行shell变量时,这篇文章出现在前几个结果中,补充一个答案似乎是合适的。
echo "$sql"
而不是 echo $sql
。 - Michael Mol感谢dimo414针对类似问题的回答,这展示了他的杰出解决方案如何工作,并表明您可以轻松地在文本中使用引号和变量:
$ ./test.sh
The text from the example function is:
Welcome dev: Would you "like" to know how many 'files' there are in /tmp?
There are " 38" files in /tmp, according to the "wc" command
#!/bin/bash
function text1()
{
COUNT=$(\ls /tmp | wc -l)
cat <<EOF
$1 Would you "like" to know how many 'files' there are in /tmp?
There are "$COUNT" files in /tmp, according to the "wc" command
EOF
}
function main()
{
OUT=$(text1 "Welcome dev:")
echo "The text from the example function is: $OUT"
}
main
read
命令并不会导出变量(大多数情况下这是好事)。以下是一种可通过一个命令导出的替代方法,可以保留或丢弃换行符,并允许根据需要混合引号样式。适用于bash和zsh。
oneLine=$(printf %s \
a \
" b " \
$'\tc\t' \
'd ' \
)
multiLine=$(printf '%s\n' \
a \
" b " \
$'\tc\t' \
'd ' \
)
export LS_COLORS=$(printf %s \
':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33' \
...
':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')
.bashrc
和.zshrc
。
=
周围加上空格。 - Nik O'Lai