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

查看:478
本文介绍了一个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

将运行脚本的命令,而不是启动一个新的外壳,并可能导致设置呼叫方的的环境。

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环境的变化。所以,源不会为我跑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环境中最常用的方法,你可能只是想硬着头皮和维护一个对每个壳的两种口味的。

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天全站免登陆