How to run an alias in a shell script?

Some options:

  1. In your shell script use the full path rather then an alias.

  2. In your shell script, set a variable, different syntax

    petsc='/home/your_user/petsc-3.2-p6/petsc-arch/bin/mpiexec'
    
    $petsc myexecutable
    
  3. Use a function in your script. Probably better if petsc is complex

    function petsc () {
        command 1
        command 2
    }
    
    petsc myexecutable
    
  4. Source your aliases

    shopt -s expand_aliases
    source /home/your_user/.bashrc
    

You probably do not want to source your .bashrc, so IMO one of the first 3 would be better.


Aliases are deprecated in favor of shell functions. From the bash manual page:

For almost every purpose, aliases are superseded by shell functions.

To create a function and export it to subshells, put the following in your ~/.bashrc:

petsc() {
    ~/petsc-3.2-p6/petsc-arch/bin/mpiexec "$@"
}
export -f petsc

Then you can freely call your command from your shell scripts.


Shell functions and aliases are limited to the shell and do not work in executed shell scripts. Alternatives for your case:

  • (if you do not bother to use mpiexec instead of petsc) Add $HOME/petsc-3.2-p6/petsc-arch/bin to your PATH variable. This can be done by editing ~/.profile and appending:

    PATH="$HOME/petsc-3.2-p6/petsc-arch/bin:$PATH"
    

    Re-login to apply these changes

  • Create the directory ~/bin and

    • make a wrapper script named petsc containing:

      #!/bin/sh
      exec ~/petsc-3.2-p6/petsc-arch/bin/mpiexec "$@"
      
    • if the program allows for it, you can skip the shellscript and make a symlink using the command:

      ln -s ~/petsc-3.2-p6/petsc-arch/bin/mpiexec ~/bin/petsc