mileszhao 发表于 2012-08-19 00:20

c程序命令行参数的诡异问题。。。望各位大神指点

具体见我写得一个demo:
simple是一个简单的linux c程序,它就是打印他的每一个命令行参数:
#./simple "select @2 from T where a > 3"
argv=[./simple]
argv=
如上直接在shell里执行是OK的,双引号里的包含空格的字符串作为一个参数

可是我写在脚本里test.sh
# cat test.sh
cmd="./simple \"select @2 from T where a > 3\""
echo $cmd
$cmd

然后我执行test.sh
#./test.sh   
./simple "select @2 from T where a > 3"
argv=[./simple]
argv=["select]
argv=[@2]
argv=
argv=
argv=
argv=
argv=[>]
argv=
好像在脚本里,双引号没起到作用了。。。
哪位大侠知道是什么原因吗? 如何在shell脚本里 传递带空格的参数吗

fdl19881 发表于 2012-08-19 00:44

$cmd就是简单的替换。
然后被替换成./simple \"select @2 from T where a > 3\"
""又被你\转义掉了。所以出现你的那种结果。
试试将$cmd换成
eval $cmd #cmd的值不变
结果就正确了。

mileszhao 发表于 2012-08-19 11:38

回复 2# fdl19881


    顶,搞定了

MMMIX 发表于 2012-08-19 14:06

mileszhao 发表于 2012-08-19 00:20 static/image/common/back.gif
可是我写在脚本里test.sh
# cat test.sh
cmd="./simple \"select @2 from T where a > 3\""
echo $cmd
$cmd

是我就會把這個角本寫成
args='select @2 from T where a > 3'
./simple "$args"
這樣會省事許多

xiyoulaoyuanjia 发表于 2012-08-20 13:14

就是先赋值变量在传多好~ :em03:

伤不起 发表于 2012-08-20 19:47

MMMIX 发表于 2012-08-19 14:06 static/image/common/back.gif
是我就會把這個角本寫成這樣會省事許多学习了。。。
页: [1]
查看完整版本: c程序命令行参数的诡异问题。。。望各位大神指点