shell 脚本可以设置调用 shell 的环境变量吗?

编程入门 行业动态 更新时间:2024-10-18 12:19:40
本文介绍了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 的环境变量吗?

本文发布于:2023-11-01 01:46:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1547889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:脚本   环境变量   shell

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!