I have a bash script where I'd like to check if an alias to activate conda runs successfully and if not raise an error. Although script runs without raising an error, none of the echo
's get printed. How could I fix it?
My ~/.bashrc
file contains
### shortcut to activate installed miniconda2
activate_conda() {
export PATH=$HOME/miniconda2/bin:/bin:/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games;
}
alias activate_conda="activate_conda"
And when I run the following bash script
#!/bin/bash
#Check if activate_conda command runs successfully
activate_conda
if [ $? -eq 0 ]; then
echo "activate_conda was successful"
exit 0
else
echo "activate_conda was not successful.
Please check your .bashrc file"
exit 1
fi
#another function to check the same alias
if activate_conda ; then
echo "Command succeeded"
else
echo "Command failed"
fi
script runs but no echo commands get printed. I think above functions are valid for actual build in terminal commands. But I am trying to run an alias
as a command.
Your script fails because neither an alias nor a shell function is accessible from within a bash script. In scripting, use either the original command instead of the alias, or include the function definition in the calling script. Eventually, you may source the code for the function into the script from another file if you want to use the same function in multiple scripts (see
help source
in the terminal).To learn how to check whether a command succeeded, see How to check if a command succeeded?.