shell脚本参数中有空格

shell脚本参数中有空格

在shell脚本中如果有空格的处理如下:

sh test.sh "hello word"
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",
原文地址:https://www.cnblogs.com/honeybee/p/6547983.html