-1

I have a homework, write a program schedsim.sh with:

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

In this:

-h: print username

-c: print x+1 (x is entered from keyboard), if don't enter x, print 1

-i: print size of filename, filename is a name of file that entered.

My code:

#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

However, when i call:

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

Error.

Sorry, my English is poor!

Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37
  • 2
    The first thing I would tell you is that your "shebang" on the first line is wrong. It shouldn't be `#i...` It should have an exclamation mark `!` instead of an `i`. As in, it should be `#!...`. – Tripp Kinetics Oct 02 '15 at 19:43
  • 2
    **What** error are you getting when you call that? Do any of the options work? Is `getopts` itself failing? – Etan Reisner Oct 02 '15 at 20:38
  • 1
    Possible duplicate of [Bash Script with Parsing Argument in Linux](http://stackoverflow.com/questions/32826395/bash-script-with-parsing-argument-in-linux) – glenn jackman Oct 02 '15 at 21:37
  • Your classmate asked this exact same question a couple of days ago: http://stackoverflow.com/q/32826395/7552 -- if you both submit it, do I get extra credit? ;) – glenn jackman Oct 02 '15 at 21:37

1 Answers1

0

Seems like you had the basic script quite close to working. I made a few changes such as adding a test for the existence of the user specified file before attempting to run ls on it and adding quotes around variables. I suggest asking your teacher how they would like you to calculate kilobytes for the area where you are using ls. du or stat may be better for this use case.

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

Another change I made was to use $(()) shell arithmetic instead of expr. Generally if one needs more powerful mathematics than $(()) can support they call out to bc (which supports floating point calculations) instead of expr.