【问题标题】:Error with getopts in shellshell 中的 getopts 错误
【发布时间】:2015-10-02 19:36:46
【问题描述】:

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

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

在这个:

-h:打印用户名

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

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

我的代码:

#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

错误。

对不起,我的英语很差!

【问题讨论】:

  • 我要告诉你的第一件事是你在第一行的“shebang”是错误的。它不应该是#i... 它应该有一个感叹号! 而不是i。如,它应该是#!...
  • 什么当您调用它时遇到错误?任何选项都有效吗? getopts 自己失败了吗?
  • 几天前你的同学问了同样的问题:stackoverflow.com/q/32826395/7552 -- 如果你们都提交,我会得到额外的分数吗? ;)

标签: bash shell getopt


【解决方案1】:

看起来你的基本脚本已经很接近工作了。我进行了一些更改,例如在尝试对其运行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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2012-12-24
    相关资源
    最近更新 更多