如何让源命令在 shell 脚本之外生效? [英] How do I get a source command to take effect outside the shell script?

查看:23
本文介绍了如何让源命令在 shell 脚本之外生效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个小脚本来获取我的 virtualenv(用于 Python 项目)目录.当我在我的项目目录中的某个地方时,我知道我的虚拟环境的venv"目录位于我当前目录的祖先之一的目录中.

I want to write a small script to source my virtualenv (for a Python project) directory. When I am somewhere inside my project directory, I know that the "venv" directory for my virtual environment is in a directory that is one of the ancestors of my current directory.

我想编写一个 shell 脚本来获取 venv/bin/activate 的源代码,并且它的效果应该在这个 shell 脚本之外持续存在.现在不会发生这种情况.

I want to write a shell script that will source venv/bin/activate and its effect should persist outside this shell script. This is not happening right now.

这是我的代码:

#!/bin/bash

#set -x

while [ $PWD != "/" ]; do
    #echo $PWD
    if [ -d "venv" ]; then
        echo "venv found in $PWD. Sourcing."
        source venv/bin/activate
        break
    else
        cd ..
    fi
done

为什么它现在不起作用,我该如何解决?

Why does it not work right now, and how can I fix it?

如果有帮助,venv/bin/activate 的内容在这里:http://pastebin.com/TZ40brsq它由 virtualenv 工具生成(通常用于 Python 项目).

If it helps, the contents of venv/bin/activate are here: http://pastebin.com/TZ40brsq It is generated by the virtualenv tool (generally used with Python projects).

推荐答案

使用在子进程中运行的 shell 脚本无法影响当前环境.

You cannot affect your current environment by using a shell script that runs in a child process.

如果你在 while 循环之前和 popd 之前添加 pushd "$(pwd)" ,你可以通过获取脚本文件而不是执行它来获得你想要的

If you add pushd "$(pwd)" before the while loop and popd after, you can get what you want by sourcing the script file instead of executing it

这篇关于如何让源命令在 shell 脚本之外生效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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