#/bin/bash# extracting command line options as parametersechowhile [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option" ;;
-b) echo"Found the -b option" ;;
-c) echo"Found the -c option" ;;
*) echo"$1 not an option";;
esac
shift
done
分离参数与选项
#/bin/bash# extracting options and parametersechowhile [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option" ;;
-b) echo"Found the -b option" ;;
-c) echo"Found the -c option" ;;
--) shift
break ;;
*) echo"$1 not an option";;
esac
shift
done#
count=1for param in"$@"doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
处理带值的选项
#/bin/bash# extracting command line and valuesechowhile [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option" ;;
-b) param="$2"echo"Found the -b option,with parameter value $param"
shift ;;
-c) echo"Found the -c option" ;;
--) shift
break ;;
*) echo"$1 not an option";;
esac
shift
done#
count=1for param in"$@"doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
使用getopt命令
getopt ab:cd -a -b test1 -cd test2 test3
#/bin/bash# extracting command line and values with getoptset -- $(getopt -q ab:cd"$@")
#echowhile [ -n "$1" ]
docase"$1"in-a) echo"Found the -a option" ;;
-b) param="$2"echo"Found the -b option,with parameter value $param"
shift ;;
-c) echo"Found the -c option" ;;
--) shift
break ;;
*) echo"$1 not an option";;
esac
shift
done#
count=1for param in"$@"doecho"Parameter #$count: $param"
count=$[ $count + 1 ]
done
getopts
#!/bin/bash# simple demonstration of the getopts command#echowhilegetopts :ab:c opt
docase"$opt"in
a) echo"Found the -a option" ;;
b) echo"Found the -b option",with value $OPTARG ;;
c) echo"Found the -c option" ;;
*) echo"Unknown option: $opt" ;;
esacdone
处理简单选项#/bin/bash# extracting command line options as parametersechowhile [ -n "$1" ]do case "$1" in -a) echo "Found the -a option" ;; -b) echo "Found the -b option" ;; -c) echo ...