shell 脚本可以设置调用 shell 的环境变量吗? [英] Can a shell script set environment variables of the calling shell?

查看:36
本文介绍了shell 脚本可以设置调用 shell 的环境变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个 shell 脚本,该脚本在运行时会设置一些环境变量,这些变量将在调用者的 shell 中保持设置.

I'm trying to write a shell script that, when run, will set some environment variables that will stay set in the caller's shell.

setenv FOO foo

在 csh/tcsh 中,或

in csh/tcsh, or

export FOO=foo

在 sh/bash 中只在脚本执行期间设置它.

in sh/bash only set it during the script's execution.

我已经知道了

source myscript

将运行脚本的命令而不是启动新的 shell,这会导致设置调用者"的环境.

will run the commands of the script rather than launching a new shell, and that can result in setting the "caller's" environment.

但问题是:

我希望这个脚本可以从 bash 或 csh 调用.换句话说,我希望任一 shell 的用户都能够运行我的脚本并更改他们的 shell 环境.所以源"对我不起作用,因为运行 csh 的用户不能获取 bash 脚本,而运行 bash 的用户不能获取 csh 脚本.

I want this script to be callable from either bash or csh. In other words, I want users of either shell to be able to run my script and have their shell's environment changed. So 'source' won't work for me, since a user running csh can't source a bash script, and a user running bash can't source a csh script.

是否有不涉及必须在脚本上编写和维护两个版本的合理解决方案?

Is there any reasonable solution that doesn't involve having to write and maintain TWO versions on the script?

推荐答案

您的 shell 进程拥有父进程环境的副本,并且无法访问父进程的环境.当您的 shell 进程终止时,您对其环境所做的任何更改都将丢失.获取脚本文件是配置 shell 环境最常用的方法,您可能只想硬着头皮为两种 shell 分别维护一个.

Your shell process has a copy of the parent's environment and no access to the parent process's environment whatsoever. When your shell process terminates any changes you've made to its environment are lost. Sourcing a script file is the most commonly used method for configuring a shell environment, you may just want to bite the bullet and maintain one for each of the two flavors of shell.

这篇关于shell 脚本可以设置调用 shell 的环境变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆