0

我在 shell 脚本中从命令提示符读取输入时遇到问题。我的脚本名称是 status.ksh,我必须从命令提示符获取参数。此脚本接受 2 个参数。第一个是“-e”,第二个是“server_name”。

当我像这样运行脚本时,

status.ksh -e server_name

echo $@

仅给出输出“server_name”,预期输出应为“-e server_name”

并将echo $1 输出设为 NULL,其中预期的输出应为“-e”。

请指导我,如何阅读获取第一个参数,即 "-e" 。

感谢和问候

4

2 回答 2

1

问题是由-e. 这是 的标志echo

   -e     enable interpretation of backslash escapes

大多数 unix 命令允许--用于分隔标志和其余参数,但echo不支持这一点,因此您需要另一个命令:

printf "%s\n" "$1"

如果您需要复杂的命令行参数解析,请务必getopts按照 Joe 的建议进行。

于 2013-04-16T12:21:03.310 回答
0

你读过这个参考吗?http://www.lehman.cuny.edu/cgi-bin/man-cgi?getopts+1

您不应该使用 $1、$2、$@ 等来解析选项。有内置程序可以为您处理这个问题。

 Example 2 Processing Arguments for a Command with Options

 The following fragment of  a  shell  program  processes  the
 arguments  for a command that can take the options -a or -b.
 It also processes the option -o, which requires  an  option-
 argument:

   while getopts abo: c
   do
         case $c in
        a | b)   FLAG=$c;;
        o)       OARG=$OPTARG;;
        \?)      echo $USAGE
           exit 2;;
        esac
   done
   shift `expr $OPTIND - 1`

更多示例:

http://linux-training.be/files/books/html/fun/ch21s05.html

http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.cmds/doc/aixcmds2/getopts.htm

http://www.livefirelabs.com/unix_tip_trick_shell_script/may_2003/05262003.htm

于 2013-04-14T15:40:17.693 回答