2010-05-23 25 views
3

我想要用户在命令行输入东西-l或-e。 例如, 。$/report.sh -e 我想if语句分裂他们做出任何决定,所以我已经试过......如何比较shell中的2个字符串?

if [$1=="-e"]; echo "-e"; else; echo "-l"; fi 

显然是行不通的,虽然 感谢

回答

9

我使用:

if [[ "$1" == "-e" ]]; then 
    echo "-e" 
else 
    echo "-l"; 
fi 

然而,分析论证,getopts可能使您的生活更轻松:

while getopts "el" OPTION 
do 
    case $OPTION in 
     e) 
      echo "-e" 
      ;; 
     l) 
      echo "-l" 
      ;; 
    esac 
done 
+0

你说“getopt”和“getopts”。他们是两回事。前者是一个独立的可执行文件,后者是内置的shell。 – 2010-05-23 02:05:02

+0

D'oh - 固定。谢谢。 – 2010-05-23 03:10:12

3

如果你想这一切在同一行(通常它使得它很难读):

if [ "$1" = "-e" ]; then echo "-e"; else echo "-l"; fi 
1

你需要方括号,发生的事情里面他们之间的空格。此外,只需使用一个=。您还需要一个then

if [ $1 = "-e" ] 
then 
    echo "-e" 
else 
    echo "-l" 
fi 

具体到-e的问题但是是它在echo特殊的意义,所以你不可能得到任何东西。如果您尝试echo -e,则不会显示任何内容,而echo -decho -f可以完成您所期望的操作。在它旁边放一个空格,或者用括号括起来,或者用其他方法将它发送到echo时不完全是-e

1

如果您只想打印用户提交的参数,则可以简单地使用echo "$1"。如果用户还没有提交任何内容,如果要恢复为默认值,则可以使用echo "${1:--l}(默认值为:-是Bash语法)。然而,如果你想真正强大和灵活的参数处理,你可以看看getopt

params=$(getopt --options f:v --longoptions foo:,verbose --name "my_script.sh" -- "[email protected]") 

if [ $? -ne 0 ] 
then 
    echo "getopt failed" 
    exit 1 
fi 

eval set -- "$params" 

while true 
do 
    case $1 in 
     -f|--foo) 
      foobar="$2" 
      shift 2 
      ;; 
     -v|--verbose) 
      verbose='--verbose' 
      shift 
      ;; 
     --) 
      while [ -n "$3" ] 
      do 
       targets[${#targets[*]}]="$2" 
       shift 
      done 
      source_dir=$(readlink -fn -- "$2") 
      shift 2 
      break 
      ;; 
     *) 
      echo "Unhandled parameter $1" 
      exit 1 
      ;; 
    esac 
done 

if [ $# -ne 0 ] 
then 
    error "Extraneous parameters." "$help_info" $EX_USAGE 
fi