Checking for the correct number of arguments

前端 未结 3 515
一向
一向 2020-12-04 08:02

How do i check for the correct number of arguments (one argument). If somebody tries to invoke the script without passing in the correct number of arguments, and checking to

3条回答
  •  醉酒成梦
    2020-12-04 08:54

    #!/bin/sh
    if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
      echo "Usage: $0 DIRECTORY" >&2
      exit 1
    fi
    

    Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

    More friendly error reporting:

    #!/bin/sh
    if [ "$#" -ne 1 ]; then
      echo "Usage: $0 DIRECTORY" >&2
      exit 1
    fi
    if ! [ -e "$1" ]; then
      echo "$1 not found" >&2
      exit 1
    fi
    if ! [ -d "$1" ]; then
      echo "$1 not a directory" >&2
      exit 1
    fi
    

提交回复
热议问题