从子shell设置父shell的变量 [英] Set a parent shell's variable from a subshell

查看:580
本文介绍了从子shell设置父shell的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在子外壳的父外壳中设置变量?

How do I set a variable in the parent shell, from a subshell?

a=3
(a=4)
echo $a

推荐答案

子shell的全部要点是不会影响调用会话.在bash中,子外壳程序是子进程,其他外壳程序有所不同,但是即使这样,子外壳程序中的变量设置也不会影响调用方.根据定义.

The whole point of a subshell is that it doesn't affect the calling session. In bash a subshell is a child process, other shells differ but even then a variable setting in a subshell does not affect the caller. By definition.

您需要一个子壳吗?如果您只需要一组,请使用花括号:

Do you need a subshell? If you just need a group then use braces:

a=3
{ a=4;}
echo $a

给出4(注意其中的空格).或者,将变量值写入stdout并在调用方中捕获它:

gives 4 (be careful of the spaces in that one). Alternatively, write the variable value to stdout and capture it in the caller:

a=3
a=$(a=4;echo $a)
echo $a

避免使用反引号``,它们已被弃用并且可能难以阅读.

avoid using back-ticks ``, they are deprecated and can be difficult to read.

这篇关于从子shell设置父shell的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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