使用命令行参数跳过Shell脚本中的函数

时间:2019-07-01 17:51:56

标签: bash shell scripting

我编写了具有不同功能的shell脚本,可以像这样从命令行调用它:

bash script.sh -i -b

因此它将运行这两个函数,而不是脚本中的其他函数。但是,我想扭转这种逻辑,如果我只是这样做

,则默认情况下让脚本运行每个函数

bash script.sh

如果我传递诸如-i -b之类的参数,我想跳过这些函数。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:1)

要实现这两种逻辑:

  1. 如果根本没有参数,请运行所有功能
  2. 对于每个传递的参数,跳过一些函数执行

您可以这样做:

#!/bin/bash

function func_i {
  echo "I am i."
}

function func_b {
  echo "I am b."
}

function main {

  # Check if there are no arguments, run all functions and exit.

  if [ $# -eq 0 ]; then
    func_i
    func_b
    exit 0
  fi

  # Parse arguments -i and -b, marking them for no execution if they are passed to the script.

  proc_i=true
  proc_b=true

  while getopts "ib" OPTION; do
      case $OPTION in
      i)
          proc_i=false
          ;;
      b)
          proc_b=false
          ;;
      *)
          echo "Incorrect options provided"
          exit 1
          ;;
      esac
  done

  # Execute whatever function is marked for run.

  if $proc_i; then func_i; fi
  if $proc_b; then func_b; fi
}

main "$@"

一些解释:

$#返回传递给脚本的参数数量。如果$#等于0,则没有参数传递给脚本。

getops接受开关-i-b,在*)情况下,所有其他开关将导致错误处理。

答案 1 :(得分:1)

您可以将默认调用的功能列表中的项目列入黑名单。像这样:

#!/bin/bash

list='a b c d e f g h i'

# define some functions
for name in $list; do
        eval "func_$name() { echo func_$name called with arg \$1; }"
done

# black list items from list
for x; do
        list=$(echo "$list" | tr -d ${x#-})
done

for name in $list; do
        func_$name $name
done

但是坦率地说,做类似的事情更有意义:

$ cat script.sh 
#!/bin/bash

list='a b c d e f g h i'
test $# = 0 && set -- $list # set default list of functions to call

# define some function
for name in $list; do
        eval "func_$name() { echo func_$name called with arg \$1; }"
done

for name; do
        func_$name $name
done
$ bash ./script.sh 
func_a called with arg a
func_b called with arg b
func_c called with arg c
func_d called with arg d
func_e called with arg e
func_f called with arg f
func_g called with arg g
func_h called with arg h
func_i called with arg i
$ bash ./script.sh c g
func_c called with arg c
func_g called with arg g