Skip to main content
added 38 characters in body
Source Link
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k
case $1 in
    -d) ;; # nothing to do
    -e) ;; # nothing to do
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

This would trigger the exit 1 if $1 is anything other than -d or -e.

Alternatively, set a flag depending on the option used and the act on it (I tend to separate parsing the command line options from acting on them):

case $1 in
    -d) dflag=1 ;;
    -e) dflag=0 ;;
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

# Getting here means:
#     - $1 was either -d or -e
#     - $dflag will show which one it was

if [ "$dflag" -eq 1 ]; then
    # act on -d option
else
    # act on -e option
fi

As ilkkachu has already elucidated, your issue (apart from the missing double quote) is one of logic (boolean operations). Above, I'm just showing another way of doing the operation. case...esac statements are often used to process command line options.

case $1 in
    -d) ;; # nothing to do
    -e) ;; # nothing to do
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

This would trigger the exit 1 if $1 is anything other than -d or -e.


As ilkkachu has already elucidated, your issue is one of logic (boolean operations). Above, I'm just showing another way of doing the operation. case...esac statements are often used to process command line options.

case $1 in
    -d) ;; # nothing to do
    -e) ;; # nothing to do
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

This would trigger the exit 1 if $1 is anything other than -d or -e.

Alternatively, set a flag depending on the option used and the act on it (I tend to separate parsing the command line options from acting on them):

case $1 in
    -d) dflag=1 ;;
    -e) dflag=0 ;;
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

# Getting here means:
#     - $1 was either -d or -e
#     - $dflag will show which one it was

if [ "$dflag" -eq 1 ]; then
    # act on -d option
else
    # act on -e option
fi

As ilkkachu has already elucidated, your issue (apart from the missing double quote) is one of logic (boolean operations). Above, I'm just showing another way of doing the operation. case...esac statements are often used to process command line options.

Source Link
Kusalananda
  • 355.8k
  • 42
  • 735
  • 1.1k

case $1 in
    -d) ;; # nothing to do
    -e) ;; # nothing to do
    *)
        echo 'Error: First argument must be either -e or -d' >&2
        exit 1
esac

This would trigger the exit 1 if $1 is anything other than -d or -e.


As ilkkachu has already elucidated, your issue is one of logic (boolean operations). Above, I'm just showing another way of doing the operation. case...esac statements are often used to process command line options.