shell中的getopts出错

时间:2015-10-02 19:36:47

标签: bash shell getopt

我有一个家庭作业,写一个程序schedsim.sh:

schedsim.sh [-h] [-c x] -i filename

在此:

-h:打印用户名

-c:打印x + 1(x从键盘输入),如果不输入x,则打印1

-i:文件名的打印大小,filename是输入文件的名称。

我的代码:

#i/bin/bash/

while getopts ":hc:i:" Option
do  
    case $Option in 
    h) 
    whoami 
    ;;
    c) a=$OPTARG
    if [ -z "$a" ]; then
        a=1
    else
        a=`expr $a + 1` 
    fi
    echo $a 
    ;;
    i) echo 'Size of file: Kylobytes' 
    ls -s $OPTARG 
    ;;
    *) echo 'sonething wrong' 
    ;;
    esac
done

但是,当我打电话时:

./schedsim.sh -c -i abc.txt

错误。

抱歉,我的英语很差!

1 个答案:

答案 0 :(得分:0)

好像你的基本脚本非常接近工作。我做了一些更改,例如在尝试在其上运行ls并在变量周围添加引号之前,为用户指定文件的存在添加测试。我建议您的老师询问您希望如何计算使用ls区域的千字节数。 dustat可能更适合此用例。

#!/bin/bash/

while getopts ":hc:i:" Option
do
    case "$Option" in
    h) whoami
       ;;
    c) a=$(( $OPTARG + 1 ))
       printf "$a\n"
       ;;
    i) if ! [ -f "$OPTARG" ]
       then printf "File does not exist\n"
       else printf "Size of file: Kylobytes: "
            ls -s "$OPTARG"
            printf "\n"
       fi
       ;;
    *) printf "something wrong\n"
       ;;
    esac
done

我做的另一项更改是使用$(()) shell算法而不是expr。通常,如果需要比$(())支持更强大的数学,他们会调用bc(支持浮点计算)而不是expr