从文件执行 bash 函数

从文件执行 bash 函数

我有一个包含几个函数的 bash 文件。是否可以使用命令行从文件中运行函数?

答案1

你可以创建脚本文件,定义一些函数,并运行作为第一个参数给出的函数$1。就像这样:

#!/bin/bash

function1() {
  do whatever ...
}

function2() {
  do whatever ...
}

case "$1" in
  function1)    # this is the name of the argument triggering the function - could be different, for instance f1
    function1   # this is the name of the function to run
    ;;

  function2)    # this is the name of the argument triggering the function - could be different, for instance f2
    function2   # this is the name of the function to run
    ;;

  *)
    echo "Usage: $0 {function1|function2}"
    ;;
esac

相关内容