Locations of visitors to this page

Friday, June 12, 2009

Bash quoting Bash的引号的转义

bash quoting
Bash的引号

Bash的单引号/双引号有何区别, 如何转义


提问:
vi test.sh
#!/bin/bash
stime=`date +'%Y-%m-%d %H:%M:%S'`
etime=`date -d '1 day' +'%Y-%m-%d %H:%M:%S'`
echo $stime
echo $etime
echo "mysql –hx.x.x.x -utest -ptest -P3306 --column-names=false -e 'select *  from test where ttime >= '"$stime"' and ttime <= '"$etime"';' dbtest"
mysql –hx.x.x.x -utest -ptest -P3306 --column-names=false -e 'select * from test where ttime >= "$stime" and ttime <= "$etime";' dbtest

bash test.sh
2009-06-11 18:25:21
2009-06-12 18:25:21
mysql –hx.x.x.x -utest -ptest -P3306 --column-names=false -e 'select * from test where ttime >= '2009-06-11 18:25:21' and ttime <= '2009-06-12 18:25:21';' dbtest
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '18:26:17 and ttime <= 2009-06-12 18:26:17' at line 1

这是为什么呢,为什么时间变量传不进去


回答:
mysql命令中, 字符串用单引号或双引号引起来都可以, 所以下面演示分别在shell/mysql命令中用单双引号,组合起来一共四种情况


1.
# PIG=jyy


2.
shell用双引号, mysql命令中的字符串用单引号
因为shell中用的是双引号, 所以$PIG变量被替换为jyy
# mysql -u root -e "select '$PIG'"
+-----+
| jyy |
+-----+
| jyy |
+-----+


3.
shell用双引号, mysql命令中的字符串也用双引号
双引号中的双引号必须转义
# mysql -u root -e "select \"$PIG\""
+-----+
| jyy |
+-----+
| jyy |
+-----+


4.
shell用单引号, mysql命令中的字符串用双引号
单引号中不替换变量,所以得将$PIG放在单引号外面,才能让shell自动替换它, 其实就是'select 双引号' + $PIG + '双引号'
# mysql -u root -e 'select "'$PIG'"'
+-----+
| jyy |
+-----+
| jyy |
+-----+


5.
shell用单引号, mysql命令中的字符串也用单引号
单引号中的单引号不能用反斜杠转义, 所以使用另一种格式$+单引号字符串, $PIG同样在单引号外面, $'select 转义的单引号' + $PIG + $'转义的单引号'
# mysql -u root -e $'select \''$PIG$'\''
+-----+
| jyy |
+-----+
| jyy |
+-----+



外部链接:
3.1.2 Quoting - Bash Reference Manual
Chapter 5. Quoting - Advanced Bash-Scripting Guide
3.3. Quoting characters - Bash Guide for Beginners



-fin-

No comments:

Website Analytics

Followers