带有参数的shell脚本

时间:2012-01-17 13:45:19

标签: linux bash shell sh

#!/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'  ?

以上是我想看我的剧本

我希望能够像这样启动它

myscript.sh -a -b -c 10

myscript.sh

myscript.sh -a -c 10

myscript.sh -c 10

等等

4 个答案:

答案 0 :(得分:3)

在你的shell上键入'man getopt',然后按照说明操作。

答案 1 :(得分:1)

使用这样的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

答案 2 :(得分:0)

您可以查看一下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

答案 3 :(得分:0)

相关问题