在shell脚本中如果有空格的处理如下:
sh test.sh "hello word"
#!/bin/bash source /etc/profile echo $1 exit 0
echo $1 得到的是hello,而不是hello word.
正确的写法如下:
vi test.sh
#!/bin/bash source /etc/profile echo "$1" echo "$2" echo "$3" exit 0
测试:
sh test.sh "hello word" "ni hao a" "how are you"
输出:
hello word ni hao a how are you
注意:
- 传递参数时要加上双引号,即是变量引用也要加上参数。 如: sh “ni hao ” ; sh “$STR_WITH_SPACE”
- 脚本中取参数时也要用双引号: “$1”,
重要
测试时发现 $变量不用加引号,传递的字符串参数加上双引号就好用,跟上面的说法有点矛盾。。。
#!/bin/bash source /etc/profile # $1不用加引号 echo $1 echo $2 echo $3 exit 0
sh test.sh "hello word" "ni hao a" "how are you"
输出
hello word ni hao a how are you