我可以出口到从bash脚本环境的变量,而不采购呢? [英] Can I export a variable to the environment from a bash script without sourcing it?

查看:110
本文介绍了我可以出口到从bash脚本环境的变量,而不采购呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的剧本

export.bash

 #!在/ usr /斌/ bash的ENV
出口VAR =HELLO,VARABLE

当我执行脚本,并尝试访问 $ VAR 我没有得到任何价值!

 回声$ VAR

有没有办法访问到 $ VAR 只需执行 export.bash 没有采购呢?


解决方案

  

有没有办法访问到 $ VAR 只需执行 export.bash 没有采购呢?


快速的答案:否

但有几个可能的解决方法。

最明显的,你已经提到过,就是用执行脚本调用程序的环境:

  $猫set-vars1.sh
出口FOO = BAR
$。 set-vars1.sh
$回声$ FOO
酒吧

另一种方法是有脚本,而不是设置一个环境变量,将设置环境变量打印命令:

  $猫set-vars2.sh
#!/斌/庆典回声出口FOO = BAR
$ $的eval(./ set-vars2.sh)
$回声$ FOO
酒吧

注意, $(...)将加盟输出成一条线。如果你有超过一件事来设置,你应该让他们仍然连接在一起后,有效增加分号打印命令。

第三种方法是有一个脚本,设置环境变量(S)内,然后调用与环境特定的命令:

  $猫set-vars3.sh
#!/斌/庆典出口FOO = BAR
EXEC$ @
$ ./set-vars3.sh printenv | grep的FOO
FOO = BAR

这最后一种方法可以是相当有用的,但它的不方便交互使用,因为它不会给你在当前的shell设置(与所有其它设置和历史,你已经建立了)。

suppose that I have this script

export.bash :

#! /usr/bin/env bash
export VAR="HELLO, VARABLE"

when I execute the script, and try to access to the $VAR I get no value !

echo $VAR

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

解决方案

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

Quick answer: No.

But there are several possible workarounds.

The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

$ cat set-vars1.sh 
export FOO=BAR
$ . set-vars1.sh 
$ echo $FOO
BAR

Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

$ cat set-vars2.sh
#!/bin/bash

echo export FOO=BAR
$ eval $(./set-vars2.sh)
$ echo $FOO
BAR

Note that the $(...) will join the output into a single line. If you have more than one thing to set, you should add semicolons to the printed commands so they're still valid after being joined together.

A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

$ cat set-vars3.sh
#!/bin/bash

export FOO=BAR
exec "$@"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR

This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).

这篇关于我可以出口到从bash脚本环境的变量,而不采购呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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