how to recognize \n in bash
質問
Have such script:
#! /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
But for every \n it gives me "Pager set to stdout", can i avoid this, i know that when echoing it i must use -e option, yet i read some material about ANSI-C quoting, but nowhere examples how to use it.
I tried to do so
mysql --host=l --port=0 --user=r --password='!' --execute="$( echo -e "$accum" )"
but it hasnt effect and i think call for echo will increase runtime.
解決
@pgl's answer is the best approach for this case, but if you actually did need to embed linefeeds in a variable value the simplest thing to do is to use bash's $'...'
form of quoting:
accum=$'use yola_test;\n'
...
accum="${accum}CALL add_new_enterprise(\"$title\");"$'\n'
...etc
Note that the second example above uses a mix of quote types; double-quotes for the first part to allow variable interpolation, and then $'...'
for the part that needs escape sequence interpretation.
BTW, another approach would be to define a variable to hold the newline:
nl=$'\n'
accum="use yola_test;${nl}"
...
accum="${accum}CALL add_new_enterprise(\"$title\");${nl}"
...etc
他のヒント
The "PAGER set to stdout" is from MySQL - to stop it displaying, just remove instances of \n from your code; you don't need them.