#!/bin/bash
set -e
TEMP=getopt -o m:s:v -n 'xxx.sh' -- "$@"
eval set -- "$TEMP"
_mode=clean
_dist=false
_sku=vena
_variant=eng
while true; do
case $1 in
-m) _mode=$2;shift 2;;
-s) _sku=$2;shift 2;;
-v) _variant=$2;shift 2;;
--) shift; break ;;
*) echo "Error while parsing arguments, abort!"; exit 1;;
esac
done
幾點說明:
set -e and set -x
If you write shell scripts, you definitely need to know about two nice features that can be enabled through the set builtin:
set -e: Enables checking of all commands. If a command exits with an error and the caller does not check such error, the script aborts immediately. Enabling this will make your scripts more robust. But don’t wait until your script is “complete” to set the flag as an afterthought, because it will be a nightmare to fix the scrip to work with this feature enabled. Just write set -e as the very first line of your code; well… after the shell bang.set -x: If you are writing simple scripts that are meant to, well, script the execution of a few tasks (as opposed of being full-flown programs written in shell), set this flag to trace the execution of all commands. This will make the interpreter print each command right before it is executed, so it will aid you in knowing what is happening at any point in time.