2011-11-08 43 views
2

有這樣的腳本:如何 n識別在bash

#! /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它給了我「尋呼機組到標準輸出」,我能避免這個,我知道,呼應時,我必須用-e選項,但我讀了一些關於ANSI-C引用的材料,但沒有例子如何使用它。

我試圖這樣做

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

,但它未效應,我想呼籲的回聲會增加運行時間。

回答

3

@ PGL的回答是這種情況下,最好的辦法,但如果你真的沒有需要嵌入換行符在變量值做最簡單的事情就是使用bash的$'...'形式引用的:

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

註上面的第二個例子使用了多種報價類型;第一部分用雙引號表示可變插值,然後$'...'表示需要轉義序列解釋的部分。

BTW,另一種方法是定義一個變量來保存換行符:

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

,然後我做「echo -e $ accum」在輸出中沒有換行(( – Yola

+1

)試試echo -e「$ accum」' - 雙引號是必要的,以防止外殼轉換換行符(和製表符和...)轉換爲單詞分隔,然後「回聲」變成空格。 –

1

「設置爲標準輸出的PAGER」來自MySQL--爲了停止它的顯示,只需從您的代碼中移除\ n的實例;你不需要它們。

+0

是的,謝謝,我知道這一點。 – Yola