0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Linux】特定ディレクトリでAnaconda環境を自動activate/deactivateする方法

Last updated at Posted at 2025-04-26

Linuxサーバーで、特定のディレクトリ配下にいる間、Anaconda環境を自動でactivate、 ディレクトリを離れたら自動でdeactivateする方法を解説します。

目的

  • /home/hoge/open-webui 配下なら、常に openwebui-env 環境が activate される
  • /home/hoge/open-webui外に出たら、自動で deactivate

手順

① 必要なディレクトリ・ファイルを作成

まず、対象ディレクトリに .conda/env_name ファイルを作成します。

mkdir -p /home/hoge/open-webui/.conda
echo "openwebui-env" > /home/hoge/open-webui/.conda/env_name

openwebui-env の部分は、実際にactivateしたいAnaconda環境名に変更してください。


.bashrc もしくは .zshrc にスクリプトを追記

エディタで .bashrc または .zshrc を開きます。

nano ~/.bashrc

ファイルの末尾に、以下を追記します。

# ==== Auto Conda Activate/Deactivate based on Directory (配下も対応版) ====

# 設定(対象ディレクトリと環境名)
export AUTO_CONDA_ENV_PATH="/home/hoge/open-webui"
export AUTO_CONDA_ENV_NAME="openwebui-env"
export AUTO_CONDA_ACTIVATED=0

function cd() {
    builtin cd "$@" || return

    if [[ "$PWD" == $AUTO_CONDA_ENV_PATH* ]]; then
        # $PWDがAUTO_CONDA_ENV_PATHで始まるなら
        if [[ "$CONDA_DEFAULT_ENV" != "$AUTO_CONDA_ENV_NAME" ]]; then
            conda activate "$AUTO_CONDA_ENV_NAME"
            export AUTO_CONDA_ACTIVATED=1
        fi
    else
        if [[ "$AUTO_CONDA_ACTIVATED" == 1 ]]; then
            conda deactivate
            export AUTO_CONDA_ACTIVATED=0
        fi
    fi
}

③ 設定を反映

書き込みが終わったら、設定を反映します。

source ~/.bashrc

(または source ~/.zshrc


動作確認例

現在の場所 Conda環境
/home/hoge/open-webui activate(on)
/home/hoge/open-webui/subdir1/ activate(on)
/home/hoge/open-webui/another/dir/ activate(on)
/home/hoge/other-project/ deactivate(off)
/home/hoge/ deactivate(off)

補足:base 環境を自動起動させたくない場合

Condaがログイン時に自動でbase環境をactivateしないようにしておくとさらに快適です。

conda config --set auto_activate_base false
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?