0

I've got another bash-script problem I simply couldn't solve. It's my simplified script showing the problem:

while getopts "r:" opt; do
case $opt in

  r)
    fold=/dev
    dir=${2:-fold}

     a=`find $dir -type b | wc -l`
     echo "$a"
  ;;
esac
done

I calling it by:

  ./sc.sh -r /bin

and it's work, but when I don't give a parameter it doesn't work:

  ./sc.sh -r

I want /dev to be my default parameter $2 in this script.

2 Answers 2

3

There may be other parameters before, don't hard-code the parameter number ($2).

The getopts help says

When an option requires an argument, getopts places that argument into the shell variable OPTARG.
...
[In silent error reporting mode,] if a required argument is not found, getopts places a ':' into NAME and sets OPTARG to the option character found.

So you want:

dir=/dev                            # the default value
while getopts ":r:" opt; do         # note the leading colon
    case $opt in
        r) dir=${OPTARG} ;;
        :) if [[ $OPTARG == "r" ]]; then
               # -r with required argument missing.
               # we already have a default "dir" value, so ignore this error
               :
           fi
           ;;
    esac
done
shift $((OPTIND-1))

a=$(find "$dir" -type b | wc -l)
echo "$a"
Sign up to request clarification or add additional context in comments.

Comments

0

This works for me:

#!/bin/bash

while getopts "r" opt; do
case $opt in

  r)
    fold=/dev
    dir=${2:-$fold}

     echo "asdasd"
  ;;
esac
done

Remove the colon (:) in the getopts argument. This caused getopt to expect an argument. (see here for more information about getopt)

3 Comments

I tried this before. Still doesn't work when I calling it without parameter: ./sc.sh -r /// error: ./sc.sh: option requires an argument -- r
Could you please help me with the same problem but with conditional statement "if". It's also return an error. The code looks like this: if [ $1 != -r ]; then fold=/dev dir=${1:-$fold} a=find $dir -type b | wc -l echo "$a" fi
Ok, I just got this ([[ $1 != -r ]])! Don't bother then and thanks in advance for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.