Bash 脚本不采购 [重复]

问题描述 投票:0回答:1

在我保存其他 bash 脚本的文件夹中,我创建了这个:

#! /bin/bash

source $(poetry env info --path)/bin/activate

在名为

poetry_activate
的文件中。在 bash 终端中,自动完成工作,当我输入
poetry_activate
时,虚拟环境没有加载...

但是,如果我在终端中执行

source $(poetry env info --path)/bin/activate
,它会起作用。如果我这样做它也有效
. poetry_activate
...

有没有办法让脚本

poetry_activate
起作用?

bash python-poetry
1个回答
2
投票

当您执行脚本时,您会启动一个子shell;当子 shell 退出时(在这种情况下,

poetry_activate
脚本退出),在子 shell 中进行的变量赋值将“丢失”。

正如您所发现的,当您 source 脚本(

. poetry_activate
source poetry_activate
)时,不会启动子 shell,而是在当前 shell 中执行命令(在脚本中)。

要消除子 shell,同时也不需要

source
脚本,您可以用函数替换 shell 脚本,例如:

poetry_activate() { source $(poetry env info --path)/bin/activate; }

# or

poetry_activate() {
    source $(poetry env info --path)/bin/activate
}

注意事项:

  • 在第一个示例中,尾随
    ;
    需要将代码与结束
    }
  • 分开
  • 将此添加到您的
    .profile
    .bashrc
  • 假设您的
    PATH
    已配置,因此操作系统可以找到
    poetry

现在不再引用脚本,而是引用函数;从命令行引用函数的示例:

$ poetry_activate
© www.soinside.com 2019 - 2024. All rights reserved.