提取在shell脚本中使用的环境变量。

huangapple go评论62阅读模式
英文:

Extract Environment Variables used in a shell script

问题

有一种方法可以提取脚本使用的所有环境变量吗?
我有一些大型脚本,需要使用多个环境变量才能正常工作。

但是阅读所有的代码并手动复制我找到的所有环境变量“调用”将非常乏味,并且有可能漏掉一些!

有没有一种脚本或插件可以执行这种工作?

例如:

teste.sh:
  if [ ! -z "$CI_COMMIT_TAG" ] ; then
  export DOCKER_IMAGE_FULL_NAME="$REGISTRY_URL/$DOCKER_IMAGE_NAME:$CI_COMMIT_TAG"
  else
  export DOCKER_IMAGE_FULL_NAME="$REGISTRY_URL/$DOCKER_IMAGE_NAME:pid$CI_PIPELINE_ID"
  fi


找到的变量:
$CI_COMMIT_TAG
$REGISTRY_URL
$DOCKER_IMAGE_NAME
$CI_PIPELINE_ID
英文:

There's some way to extract all the environment variables that a script use?
I have some big scripts that use several environment variables to work properly.

But read all the code and manually copy all the environment variables "calls" that I find would be very boring and with a high change os miss a few of them!

There's some sort of script or plugin that does this kind of job?

And example would be:

teste.sh:
  if [ ! -z "$CI_COMMIT_TAG" ] ; then
  export DOCKER_IMAGE_FULL_NAME="$REGISTRY_URL/$DOCKER_IMAGE_NAME:$CI_COMMIT_TAG"
  else
  export DOCKER_IMAGE_FULL_NAME="$REGISTRY_URL/$DOCKER_IMAGE_NAME:pid$CI_PIPELINE_ID"
  fi


Variables Found:
$CI_COMMIT_TAG
$REGISTRY_URL
$DOCKER_IMAGE_NAME
$CI_PIPELINE_ID

答案1

得分: 1

远非完美,但您可以使用正则表达式提取形式为 `$var`、`${VAR}`、`${Var-default}`、`${VAR:+alternative}` 等的所有变量扩展。

grep -io '${?[[:alnum:]_]+[}:+-=?]?' yourscript.sh | tr -d '{}:+-=?'


等效的扩展 grep 调用:

grep -ioE '${?[[:alnum:]_]+[}:+-=?]?' yourscript.sh | tr -d '{}:+-=?'


首先,所有看起来像变量的内容被 grepped,然后从输出中删除定界符。
英文:

Far from perfect, but you could use a regular expression to extract all variable expansions of the forms $var, ${VAR}, ${Var-default}, ${VAR:+alternative} and others.

grep -io '${\?[[:alnum:]_]\+[}:+-=?]\?' yourscript.sh | tr -d '{}:+-=?'

The equivalent extended grep call:

grep -ioE '$\{?[[:alnum:]_]+[}:+-=?]?' yourscript.sh | tr -d '{}:+-=?'

First, everything that looks like a variable is grepped and then delimiters are removed from the output.

huangapple
  • 本文由 发表于 2023年4月1日 00:18:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75900704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定