欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

学习笔记-位置参数轮替(shift)

程序员文章站 2022-03-04 19:37:34
...

例子:
如果一个脚本可以接受一堆的参数,而求所有参数的和
sum.sh 4 5 23 35 ….n

#!/bin/bash
#
declare -i sum=0

for i in `seq 1 $#`;do
        let sum=$sum+$1
        shift
done
echo $su
这里写代码片

学习笔记-位置参数轮替(shift)

#!/bin/bash
#
[ $# -lt 2 ] && echo "Too less arguments,quit" && exit 3

if [[ "$1" == "-u" ]]; then
        userName="$2"
        shift 2
fi

if [ $# -ge 2 ] && [ "$1" == "-v" ];then
        varFlag="$2"
fi

varFlag=${varFlag:-0}

if [ -n $varFlag ];then
        if ! [[ $varFlag =~ [012] ]];then
                echo "Wrong parameter."
                echo "Usage:`basename $0` -u Username -v {1|2}"
                exit 4
        fi
fi

if [ $varFlag -eq 1 ];then
        echo "2"
        echo "`grep "^userName" /etc/passwd | cut -d: -f1,3,4,6`"
elif [ $varFlag -eq 2 ];then
        echo "1"
                echo "`grep "^userName" /etc/passwd | cut -d: -f1,3,4,6,7`"
else
        echo "`grep "^userName" /etc/passwd | cut -d: -f1,3,4`"
        echo "3"
fi

学习笔记-位置参数轮替(shift)

#!/bin/bash
#
#echo $1
#echo $2
#echo $3
#echo $4
[ $# -lt 2 ] && echo "too less argments,quit" && exit 3
[ -n $4 ] && $4=0
if [ "$1" == "-u" ] && [ "$3" == "-v" ]; then
        if [ $4 -eq 1 ];then
                echo "`grep -e "^kayshi" /etc/passwd | cut -d: -f1,3,4,6`"
        elif [ $4 -eq 2 ];then
                echo "`grep -e "^kayshi" /etc/passwd | cut -d: -f1,3,4,6,7`"
        else
                echo "erro num"
        fi
elif [ "$1" == "-u" ];then
        echo "`grep -e "^kayshi" /etc/passwd | cut -d: -f1,3,4`"
else
        echo "option is invaild"
fi
#!/bin/bash
#
[ $# -lt 2 ] &&  echo "too less arguments,qiut" && exit 5

if [ "$1" == "-u" ];then
    userName=$2
    shift 2
else
    echo -e "option is wrong:$1\nhelpinfo: ./script.sh -u username"
    exit 8
fi

if ! grep "^$userName\>" /etc/passwd >> /dev/null; then
    echo "$userName not exist"
    exit 6
fi

if [ "$1" == "-v" ];then
    flag=$2
else
    echo -e "option is wrong:$1\nhelpinfo: ./script.sh -u username -v {1|2}"
    exit 9
fi

if [ -n "$flag" ];then
    if [ $flag == 1 ];then
        grep "^$userName\>" /etc/passwd | cut -d: -f1,3,4,6
    elif [ $flag == 2 ];then
        grep "^$userName\>" /etc/passwd | cut -d: -f1,3,4,6,7
    else
        echo "argument is wrong: -v {1|2}"
    fi
else

        grep "^$userName\>" /etc/passwd | cut -d: -f1,3,4 || echo "$username in not exist"
fi
相关标签: linux