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

例子:
如果一个脚本可以接受一堆的参数,而求所有参数的和
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
这里写代码片

这里写图片描述

#!/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

这里写图片描述

#!/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

猜你喜欢

转载自blog.csdn.net/weixin_36209467/article/details/82155407
今日推荐