2

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.

How to check if a command succeeded?

Dan
  • 13,119
Jenny
  • 591
  • 2
    Aliases aren't expanded by default in scripts (only in interactive shells) - although that shouldn't matter in this case since you have a function of the same name – steeldriver Jun 05 '19 at 01:18

1 Answers1

2

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?.

vanadium
  • 88,010
  • Hi Vanaium: Thanks! But what do you mean by full command instead of the alias? – Jenny Jun 05 '19 at 16:44
  • 1
    In my answer, I changed "full command" to "original command": instead of writing the alias in the script, you should just write out the original command. – vanadium Jun 05 '19 at 17:25