变量在〜/ .bashrc中设置并在shellscript中访问它们(variables set in ~/.bashrc and accessing them in shellscript)

编程入门 行业动态 更新时间:2024-10-15 04:27:54
变量在〜/ .bashrc中设置并在shellscript中访问它们(variables set in ~/.bashrc and accessing them in shellscript)

在返回非交互式shell 之前 ,我在.bashrc的顶部有这个

FOO="BAR"; export FOO echo "HELLO WORLD" # If not running interactively, don't do anything [ -z "$PS1" ] && return

我在我的homedirectory中有一个脚本test.sh:

#!/bin/bash echo "A" echo $FOO echo "B"

我执行test.sh. 输出:

A B

2个问题:

为什么我看不到$ FOO的价值? 为什么我没有看到“你好世界”?

编辑:我认为带#!/ bin / bash的脚本会触发一个子shell,它会再次调用.bashrc,我错了吗?

编辑:即使我从其他主机调用脚本,我也看不到任何值。 即使这样,.bashrc也会被执行???

ssh remotehost "/home/username/test.sh"

I have this at the very top of my .bashrc, before the return for non-interactive shells

FOO="BAR"; export FOO echo "HELLO WORLD" # If not running interactively, don't do anything [ -z "$PS1" ] && return

I have a script test.sh in my homedirectory with this:

#!/bin/bash echo "A" echo $FOO echo "B"

I execute test.sh. The output:

A B

2 Questions:

Why don't I see the value of $FOO? Why don't I see the "HELLO WORLD"?

edit: I thought the script with #!/bin/bash triggers a subshell which will call the .bashrc again, am I that wrong?

edit: Even If I do call the script from another host I won't see any values. Not even then , the .bashrc will be executed???

ssh remotehost "/home/username/test.sh"

最满意答案

.bashrc仅为非登录交互式shell自动获取。 通常,你会放. .bashrc . .bashrc靠近.bash_login文件的开头,以确保.bashrc来源于登录和非登录交互式shell。

.bashrc不会自动为非交互式shell提供源代码,例如执行shell脚本时启动的shell。

由于您从.bashrc导出FOO ,因此test.sh看到FOO具有空值的事实告诉我您正在从登录shell运行脚本。 从提示打印BAR echo $FOO ? 如果确实如此,我会感到惊讶,而test.sh却没有。

.bashrc is only sourced automatically for non-login interactive shells. Often, you would put . .bashrc near the beginning of your .bash_login file, to ensure that .bashrc is sourced for both login and non-login interactive shells.

.bashrc is not sourced automatically for non-interactive shells, such as those started when you execute a shell script.

Since you export FOO from .bashrc, the fact that test.sh sees FOO having a null value tells me that you are running the script from a login shell. Does echo $FOO from the prompt print BAR? I would be surprised if it did and test.sh did not.

更多推荐

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

发布评论

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

>www.elefans.com

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