消毒用命令或bash脚本环境? [英] Sanitize environment with command or bash script?
问题描述
在Bash shell中,我想用命令运行时消毒环境的第一件事。
我想取消设置所有环境变量,只设置了至关重要的壳功能的人,再加上那些通过我的脚本所需要的那些来完成它的任务。
有没有办法在一个简单和干净的方式做到这一点?
您可以使用 ENV
和一个包装脚本:
#!/斌/庆典
ENV -i /path/to/main_script.sh
从男人ENV
:
-i,--ignore环境
先建立一个空的环境
块引用>您还可以,当然,只要运行脚本
ENV -i script.sh
如果你是手工运行它。不幸的是,据我可以告诉一个人不能使用该脚本家当运行庆典
到ENV
这样的;该家当只能接受两个参数的定义内核的解析。使用
ENV
或其他半可靠的解决方案EXEC -c
(这确实pretty多少同),我能想到的是使用EXEC -c $ 1,0
来用干净的环境中重新运行脚本,如果你发现它不干净。假设$ HOME
设置在不洁的环境,而不是在一个干净的设置(这是我的真实安装):#!/斌/庆典
[!$ HOME=]&功放;&安培; EXEC -C $ 0个
脚本的其余#这里In Bash shell, I want to sanitize the environment as the first thing when running with a command.
I want to unset all the environment variables and only set the ones that are critical for the shell to function, plus the ones the ones needed by my script to complete it's task.
Is there a way to do this in a simple and clean way?
解决方案You can use
env
and a wrapper script:#!/bin/bash env -i /path/to/main_script.sh
From
man env
:-i, --ignore-environment start with an empty environment
You can also, of course, just run the script as
env -i script.sh
if you are running it by hand. Unfortunately as far as I can tell one can't use the script shebang to runbash
throughenv
like this; the shebang can only accept two parameters by definition as parsed by the kernel.The other semi-reliable solution using
env
orexec -c
(which does pretty much the same) that I can think of would be to useexec -c $0
to re-run the script with a clean environment if you detect it's not clean. Assuming$HOME
is set in an unclean environment and is not set in a clean one (that's true in my install):#!/bin/bash [ "$HOME" != "" ] && exec -c $0 # rest of the script here
这篇关于消毒用命令或bash脚本环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!