具有参数输出的Bash脚本

时间:2018-10-29 16:06:01

标签: shell

  

我有任务要做

     

编写一个shell脚本evenparam.sh,它具有偶数个命令行参数,因此它具有以下语法   evenparam.sh para1 para2 [para3 para4] ...   该脚本应生成以下形式的输出:para1 = para2,para3 => para4,...。   如果未正确调用程序,请在stderr上发出用法消息,并以大于1的返回值结束脚本。   

anz=$#
counter=1
if [ $(($# % 2)) -eq 0 ]; then
    for para in $@; do
        pos1=$counter
        pos2=$(($counter+1))
        echo $pos1=$pos2
        counter=$(($counter+2))
        if [ $counter = $(($# + 1)) ]; then
            exit 0
        fi
    done
fi

anz=$# counter=1 if [ $(($# % 2)) -eq 0 ]; then for para in $@; do pos1=$counter pos2=$(($counter+1)) echo $pos1=$pos2 counter=$(($counter+2)) if [ $counter = $(($# + 1)) ]; then exit 0 fi done fi

我心中没有任何信息可做 有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

以下演示功能,请参见bash手册man bash,以供参考

#!/bin/bash

(( $#%2==0 )) || {
    echo "usage: $0 para1 para2 [para3 para4] ..."
    exit 1
}

# either using array
args=( "$@" )
for (( i=0;i<$#;i+=2 )); do
    echo "${args[i]} = ${args[i+1]}"
done

# or consuming arguments
while (( $#>0 )); do
    echo "$1 = $2"
    shift 2
done

# otherwise because printf has loop, just
printf "%s = %s\n" "$@"

答案 1 :(得分:0)

./ test1.sh para1 para2 [para3 para4]#如果我在终端中键入

输出是这样的:

 para1 = para2
 [ = para3
 para4 ] = 

我使用您的代码

args=( "$@" )
for (( i=0;i<$#;i+=2 )); do
echo "${args[i]} = ${args[i+1]}"
done