如何指定多行shell变量?

时间:2013-03-15 09:58:35

标签: bash shell

我写了一个查询:

function print_ui_hosts
{
local sql = "select ........."
print_sql "$ sql"
}

本地sql - 一个很长的字符串。查询未格式化。 如何将字符串拆分成多行?

5 个答案:

答案 0 :(得分:136)

只需在必要时插入新行

sql="
SELECT c1, c2
from Table1, Table2
where ...
"

shell将查找结束引号

答案 1 :(得分:107)

read与heredoc一起使用,如下所示:

read -d '' sql << EOF
select c1, c2 from foo
where c1='something'
EOF

echo "$sql"

答案 2 :(得分:54)

我想再给出一个答案,而其他答案在大多数情况下都足够了。

我想在多行上写一个字符串,但其内容必须是单行。

sql="                       \
SELECT c1, c2               \
from Table1, ${TABLE2}      \
where ...                   \
"

我很抱歉,如果这有点偏离主题(我不需要这个用于SQL)。但是,在搜索多行shell变量时,这篇文章出现在第一个结果中,另外一个答案似乎是合适的。

答案 3 :(得分:6)

感谢dimo414's answer to a similar question,这表明他的优秀解决方案如何运作,并且表明您可以轻松地在文本中添加引号和变量:

示例输出

$ ./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

test.sh

#!/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

答案 4 :(得分:4)

read不会导出变量(这在大多数情况下都是好事)。这是一个可以在一个命令中导出的替代方法,可以保留或丢弃换行符,并允许根据需要混合引用样式。适用于bash和zsh。

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

我承认引用的必要性让SQL变得丑陋,但它回答了标题中的(更普遍表达的)问题。

我像这样使用它

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的文件。

相关问题