Ubuntu – How to run an alias in a shell script


I have an executable file mpiexec, whose full path is ~/petsc-3.2-p6/petsc-arch/bin/mpiexec. Since I want to execute this command in different directories (without having to retype the entire path), I setup an alias in my home .bashrc file:

alias petsc="~/petsc-3.2-p6/petsc-arch/bin/mpiexec"  

which allows me to execute this mpiexec file at the command prompt easily by typing:

petsc myexecutable

I tried to write a shell script file, named script, using my new alias petsc as a command. After giving my shell script the appropriate permissions (using chmod), I tried to run the script. However, it gave me the following error:

./script: line 1: petsc: command not found

I know that I could just write the full path to the mpiexec file, but it is cumbersome to write the full path everytime that I want to write a new script. Is there a way that I can use my alias petsc inside the script file? Is there a way I can edit my .bashrc or .bash_profile to make this happen?

Best Answer

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

Related Question