1

我对 shell 脚本很陌生,所以这让我有点困惑,我似乎找不到解决方案。假设我有一个可以接受多个参数的 shell 脚本。为了举例,我可以这样称呼它:

myscript -a valA -b valB -c valC -d valD 一些/目录

现在,其中一些参数用于我的脚本本身,而其他参数用于将在我的脚本中调用的命令。因此,对于这种情况,-a、-d 和目录用于我的脚本,其他所有内容都用于命令。所以我想做这样的事情:

args=''

if [ $# == 0 ]
then
    echo "No arguments found!"
    exit 1
fi

while [ "$2" ]
do
    if [ $1 == '-a' ]
    then
        #some process here
        shift 2
    elif [ $1 == '-d' ]
    then
        #some process here
        shift 2
    else
        #add the argument to args
        shift
    fi
done
directory=$1

for file in $directory/*.txt
do 
    #call 'someCommand' here with arguments stored in args + $file
done

我试过做

args="$args $1"

然后调用命令做

someCommand "$args $file"

但是, someCommand 似乎认为整个事情是一个单一的论点。

另外,如果您发现我的脚本的其余部分有任何问题,请随时指出。它似乎有效,但我很可能会错过一些极端情况或做一些可能导致意外行为的事情。

谢谢!

4

3 回答 3

1

只需删除引号:

someCommand $args "$file"
于 2012-09-07T17:43:12.590 回答
1

使用数组。

newargs=()
newargs+="-9"
newargs+="$somepid"
kill "${newargs[@]}"
于 2012-09-07T17:25:20.283 回答
0

使用set

set man page : 如果没有选项,每个 shell 变量的名称和值都以可以重用作为输入的格式显示。输出根据当前语言环境进行排序。指定选项时,它们会设置或取消设置 shell 属性。处理选项后剩余的任何参数都被视为位置参数的值,并按顺序分配给 $1, $2, ... $n。

args=''

if [ $# == 0 ]
then
    echo "No arguments found!"
    exit 1
fi

while [ "$2" ]
do
    if [ $1 == '-a' ]
    then
        echo "Consuming $1 $2"
        shift 2
    elif [ $1 == '-d' ]
    then
        echo "Consuming $1 $2"
        shift 2
    else
        args="$args $1"
        shift
    fi
done
directory=$1

# *** call set here ***
set "$args"

for file in $directory/*.txt
do 
    # refer to the parameters using $@
    someCommand $@ $file
done
于 2012-10-10T10:24:15.617 回答