带参数的shell脚本呈现

问题描述:

#!/bin/bash 
#if present -a flag then print this echo 
#echo "A"; 
#if -b is present then print b 
#echo "B" 

#and if -c 10 present how can I read this value '10' ? 

以上就是我想看看我的剧本带参数的shell脚本呈现

,我希望能够象这样开始

myscript.sh -a -b -c 10 

myscript.sh 

myscript.sh -a -c 10 

myscript.sh -c 10 

等在shell上

型 '男人的getopt',并按照指示。

您可能会看看getopts。

下面的例子是从http://wiki.bash-hackers.org/howto/getopts_tutorial

#!/bin/bash 

while getopts ":a" opt; do 
    case $opt in 
    a) 
     echo "-a was triggered!" >&2 
     ;; 
    \?) 
     echo "Invalid option: -$OPTARG" >&2 
     ;; 
    esac 
done 

使用getopts的考虑是这样的:

arg=-1 
while getopts "c:ab" optionName; do 
    case "$optionName" in 
    a) echo "-a is present";; 
    b) echo "-b is present";; 
    c) arg="$OPTARG"; echo "-c is present [$arg]";; 
    esac 
done 
+0

最初只有-b( “myscript.sh -b” )给出了这个“./myscript.sh:选项需要一个参数 - b OPT:? “ – Lukap 2012-01-17 14:00:36

+0

对不起,我有一个错字,现在请检查更新的脚本。没有参数的选项应该在冒号':'末尾出现。 – anubhava 2012-01-17 14:08:20

+0

干净的代码... +1 – 2012-01-17 14:13:23