aibangjuxin / groovy

study groovy
1 stars 0 forks source link

Shell config #66

Open aibangjuxin opened 8 months ago

aibangjuxin commented 8 months ago

当你需要编写一个Shell脚本,其中需要定义函数并使用配置文件中的参数时,你可以遵循以下的逻辑参考和示例。假设你的脚本为 a.sh,命令行参数包括 -e 用于指定环境, -n 用于指定配置文件:

#!/bin/bash

# 默认值
env=""
config_file=""

# 处理命令行参数
while getopts "e:n:" opt; do
  case $opt in
    e)
      env="$OPTARG"
      ;;
    n)
      config_file="$OPTARG"
      ;;
    \?)
      echo "Usage: a.sh -e <environment> -n <config_file>"
      exit 1
      ;;
  esac
done

# 加载配置文件
if [ -f "$config_file" ]; then
  source "$config_file"
else
  echo "Config file not found: $config_file"
  exit 1
fi

# 定义函数
my_function() {
  echo "Environment: $env"
  echo "Database Host: $db_host"
  echo "Database Port: $db_port"
  # 添加更多的函数逻辑
}

# 调用函数
my_function

在这个示例中,你需要创建一个配置文件(例如 a.conf),并在其中定义你的配置参数,如 db_hostdb_port

# a.conf
db_host="localhost"
db_port="3306"
# 添加其他配置参数

然后,你可以运行你的脚本如下:

./a.sh -e dev-cn -n a.conf

脚本将加载配置文件,并调用函数以获取和显示相应的参数。这种方式可以根据不同的配置文件和环境轻松定制脚本的行为。