英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论