gpt4 book ai didi

bash - 在 ~/.bashrc 中设置变量并在 shell 脚本中访问它们

转载 作者:行者123 更新时间:2023-11-29 09:09:10 27 4
gpt4 key购买 nike

我把它放在我的 .bashrc 的最顶部,非交互式 shell 的返回之前

FOO="BAR"; export FOO
echo "HELLO WORLD"

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

我的主目录中有一个脚本 test.sh:

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

我执行test.sh。输出:

A

B

2 个问题:

  • 为什么我看不到 $FOO 的值?
  • 为什么我看不到“HELLO WORLD”?

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

编辑:即使我确实从另一台主机调用脚本,我也看不到任何值。即便如此,.bashrc 也会被执行???

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

最佳答案

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

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

由于您从 .bashrc 中导出 FOO,因此 test.sh 看到 FOO 有一个 null value 告诉我您正在从登录 shell 运行脚本。 echo $FOO 是否从提示打印 BAR?如果它有而 test.sh 没有,我会感到惊讶。

关于bash - 在 ~/.bashrc 中设置变量并在 shell 脚本中访问它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17219174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com