Problem Description:
When using the Linux system, sometimes you want to use a script to execute multiple commands to save time. If anaconda is installed, you need to switch the environment or close the conda environment. It stands to reason that you can pass the command in the terminal
conda activate xxx
or
conda deactivate
To activate the environment and close the environment, but if you put this command directly into the .sh script file, such as
#!/bin/bash
# 退出当前的conda环境
conda deactivate
The execution will fail, and the error content is
CommandNotFoundError: Your shell has not been properly configured to use 'conda deactivate'.
To initialize your shell, run
$ conda init <SHELL_NAME>
Currently supported shells are:
- bash
- fish
- tcsh
- xonsh
- zsh
- powershell
See 'conda init --help' for more information and options.
IMPORTANT: You may need to close and restart your shell after running 'conda init'.
The above error content means that your shell has not been properly configured to use conda deactivate
the command. To fix this, you can follow the steps he wrote to initialize Conda in the Bash shell
conda init bash
But in fact, even if you execute it, it will not have any effect after restarting your terminal, and the error remains the same
It is easy to solve the above problem
Solution:
In the script, first source your anaconda directory, the script anaconda3/etc/profile.d/conda.sh is used to load the initialization script of Conda so that the command can work normally, for conda deactivate
example
#!/bin/bash
# 加载 Conda 的初始化脚本
source /home/(你的用户名)/anaconda3/etc/profile.d/conda.sh
# 退出当前的conda环境
conda deactivate
# 检查是否已经退出conda环境
if [ -z "$CONDA_PREFIX" ]; then
echo "Conda environment is deactivated."
else
echo "Failed to deactivate Conda environment."
exit 1
fi
The above script, first modify it to your anaconda directory, and then use an if command to feedback whether you have exited the conda environment and run the test
Looking at the feedback information, it means that it is very smooth. If you have passed the test and there is no problem, you can continue to add your instructions later. For example, I want to close the conda environment first, and then execute the ROS command
Of course, in addition to deactivate/close the conda environment, activate/activate other environments is the same method