在getopt,Unix shell脚本中出现问题

use*_*638 1 unix linux shell

嗨,有人可以解决这个问题,我无法得到解决.

我无法获得-p的输出.

#!/bin/bash 

args=`getopt c:m:p $*` 

if [ $? != 0  -o $# == 0 ] 
then 
  echo 'Usage: -c <current-dir> -m <my dir> -p <argument>' 
  exit 1 
fi 

set -- $args 

for i 
do 
 case "$i" in 
         -c) shift;CURRDIR=$1;shift;shift ;; 
         -m) MYDIR=$1;shift;; 
         -p) ARGVAL=$OPTARG;; 
   esac 
done 

echo "CURRDIR = $CURRDIR" 
echo "MYDIR = $MYDIR" 
echo "ARGVAL = $ARGVAL" 

./1.sh -c "def" -m "ref" -p "ref -k ref" 
Run Code Online (Sandbox Code Playgroud)

预期产出

output -c = "def" 
-m ="ref" 
-p ="ref -k ref"
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 5

getopt的

args=`getopt c:m:p $*` 
Run Code Online (Sandbox Code Playgroud)

你需要在之后添加一个冒号p来表示-p接受一个参数.你也应该改变$*,以"$@"更好地处理的空间.

args=`getopt c:m:p: "$@"` 
Run Code Online (Sandbox Code Playgroud)

你也在混淆getopt和getopts.$OPTARG是一个getopts功能.使用普通的getopt和set,你应该简单地使用$2然后转移参数.

-p) ARGVAL=$2; shift 2;; 
Run Code Online (Sandbox Code Playgroud)

在这一点上,你已经用getopt完成了尽可能好的工作.不幸的是,-p无论你做什么,它都不会处理多字论证.为此,我们需要使用getopts.

getopts的

来自getopt和getopts:

更容易使用,通常比getopt更好,但当然不能在类似csh的shell中使用.无论如何你不应该使用它们.

这与"getopt"的工作方式完全不同.首先,因为它是一个内置的,你通常不会找到它的单独的手册页,虽然"help getopts"可能会给你你需要的东西.

旧的"getopt"被调用一次,它改变了我们在上面看到的环境.每次要处理参数时都会调用内置的"getopts",并且它不会更改原始参数.

使用getopts要简单得多.您的整个循环可以简化为:

while getopts c:m:p: flag
do 
    case "$flag" in 
        c) CURRDIR=$OPTARG;; 
        m) MYDIR=$OPTARG;; 
        p) ARGVAL=$OPTARG;; 
    esac 
done 
Run Code Online (Sandbox Code Playgroud)

无需转换,您只需$OPTARG每次都阅读以获得每个选项的价值.