【问题标题】:how to recognize \n in bash如何在bash中识别\ n
【发布时间】:2011-11-08 15:08:22
【问题描述】:

有这样的脚本:

#! /bin/bash

typeset -i i END
let END=500 i=1
remainder=1
accum="use yola_test;\n"
for ((i=1;i<=END;++i)); do 
#   str1=$( echo "$i" | md5sum | md5sum )
    title="title_$i"
#   "${str1:2:20}"
    accum="${accum}CALL add_new_enterprise(\"$title\");\n"
    let "remainder=$i % 100"
    if [ $remainder -eq 0 ]; then
        accum="${accum}SELECT count(*) as \`enterprises:\` FROM enterprise;\n"
        mysql --host=l --port=0 --user=r --password='!' --execute="$accum" 
        accum="use yola_test;\n"
    fi
done

但是对于每个 \n 它都会给我“Pager set to stdout”,我可以避免这种情况吗,我知道在回显它时我必须使用 -e 选项,但我阅读了一些关于 ANSI-C 引用的材料,但没有示例如何使用它。

我试过了

mysql --host=l --port=0 --user=r --password='!' --execute="$( echo -e "$accum" )"

但它没有效果,我认为调用 echo 会增加运行时间。

【问题讨论】:

    标签: mysql bash escaping quoting


    【解决方案1】:

    @pgl 的答案是这种情况下的最佳方法,但如果您确实需要在变量值中嵌入换行符,最简单的做法是使用 bash 的 $'...' 引用形式:

    accum=$'use yola_test;\n'
    ...
    accum="${accum}CALL add_new_enterprise(\"$title\");"$'\n'
    ...etc
    

    请注意,上面的第二个示例使用了多种引用类型;第一部分双引号允许变量插值,然后$'...' 用于需要转义序列解释的部分。

    顺便说一句,另一种方法是定义一个变量来保存换行符:

    nl=$'\n'
    accum="use yola_test;${nl}"
    ...
    accum="${accum}CALL add_new_enterprise(\"$title\");${nl}"
    ...etc
    

    【讨论】:

    • 然后我执行“echo -e $accum”输出中没有换行符((
    • 试试echo -e "$accum"——双引号是防止shell将换行符(和制表符和...)变成分词符的必要条件,echo 然后变成空格。跨度>
    【解决方案2】:

    “PAGER 设置为标准输出”来自 MySQL - 要停止显示,只需从代码中删除 \n 的实例;你不需要它们。

    【讨论】:

      猜你喜欢
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-01
      相关资源
      最近更新 更多