2

I have got a bash script which needs 5 arguments. I want to print usage and missing argument error if any of them are missing and exit there. Also help option which just print $usage.

#script.sh
usage="$0 param1 param2 param3 param4 param5
         param1 is ..
         param2 is ..
         param3 is ..
         param4 is ..
         param5 is .."

#if script.sh
# prints $usage and all param missing

#if script.sh param1 param2 param3
# print $usage and param4 and param5 missing and exit and so on

# script.sh -h
# just print $usage
SSh
  • 179
  • 2
  • 13
  • Consider using `getopts`, see e.g. [here](http://stackoverflow.com/a/11279500/5128464). – vlp Oct 18 '15 at 21:05

3 Answers3

8

You can use

var=${1:?error message}

which stores in $var the value of $1 if it is set, and if not, displays the error message and stop the execution.

For example:

src_dir="${1:?Missing source dir}"
dst_dir="${2:?Missing destination dir}"
src_file="${3:?Missing source file}"
dst_file="${4:?Missing destination file}"

# if execution reach this, nothing is missing

src_path="$src_dir/$src_file"
dst_path="$dst_dir/$dst_file"
echo "Moving $src_path to $dst_path"
mv "$src_path" "$dst_path"
Alvaro Gutierrez Perez
  • 3,669
  • 1
  • 16
  • 24
2

Here's one way to do it:

usage() {
    echo the usage message
    exit $1
}

fatal() {
    echo error: $*
    usage 1
}

[ "$1" = -h ] && usage 0

[ $# -lt 1 ] && fatal param1..param5 are missing
[ $# -lt 2 ] && fatal param2..param5 are missing
[ $# -lt 3 ] && fatal param3..param5 are missing
[ $# -lt 4 ] && fatal param4 and param5 are missing
[ $# -lt 5 ] && fatal param5 is missing

# all good. the real business can begin here
janos
  • 120,954
  • 29
  • 226
  • 236
0

Another way to do it.

if [ $# -ne 5 ]
then
    echo "$0 param1 param2 param3 param4 param5
          You entered $# parameters"
    PC=1
    for param in "$@"
    do
       echo "param${PC} is $param"
       PC=$[$PC +1]
    done
fi
papkass
  • 1,261
  • 2
  • 14
  • 20