bash脚本:将脚本参数的子集传递给命令

时间:2012-09-07 17:21:26

标签: bash shell

我对shell脚本很新,所以它让我感到困惑,我似乎无法找到解决方案。假设我有一个可以采用多个参数的shell脚本。为了举例,我可以称之为:

myscript -a valA -b valB -c valC -d valD some / directory

现在,其中一些参数适用于我的脚本本身,而其他参数适用于将在我的脚本中调用的命令。所以对于这种情况,-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"

然而,某些命令似乎认为整件事只是一个论点。

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

谢谢!

3 个答案:

答案 0 :(得分:1)

使用数组。

newargs=()
newargs+="-9"
newargs+="$somepid"
kill "${newargs[@]}"

答案 1 :(得分:1)

只需删除引号:

someCommand $args "$file"

答案 2 :(得分: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