How to run an alias in a shell script?

302,515

Solution 1

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.

Solution 2

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.

Solution 3

In bash 4 you can use special variable: $BASH_ALIASES.

For example:

$ alias foo="echo test"
$ echo ${BASH_ALIASES[foo]}
echo test
$ echo `${BASH_ALIASES[foo]}` bar
test bar

Alternatively define as variable then use command substitution or eval.

So for example, instead of defining the alias such as:

alias foo="echo test"

define it as:

foo="echo test"

instead. Then execute it by either:

find . -type f -exec sh -c "eval $foo" \;

or:

find . -type f -exec sh -c "echo `$foo`" \;

Solution 4

ALIASES
   ...
   Aliases are not expanded when the shell is not interactive, unless the expand_aliases shell option is set using shopt (see the description of shopt under SHELL BUILTIN COMMANDS
   below).

So the real answer to this question, for those looking to use actual aliases in shell scripts instead of alternatives to them, is:

#!/bin/bash

shopt -s expand_aliases

alias foo=bar

foo whatever

As for why I'd want to do this: Due to unusual circumstances, I need to trick a Dockerfile into thinking it's a shell script.

Solution 5

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
      
Share:
302,515

Related videos on Youtube

Paul
Author by

Paul

Senior Aerospace Engineer Specialties: Multiphysics Modeling and Simulation Heterogeneous Multiscale Methods Computational Orbital Mechanics Computational Electromagnetics Computational Solid Mechanics Computational Fluid Dynamics Computational Heat Transfer Finite Difference Methods Computational Robotics Finite Element Methods Finite Volume Methods Numerical Analysis Calculus Jokes Analogies Education: PhD. Computational Science M.S. Computational Science M.S. Applied Mathematics B.S. Mathematics and Spanish Past: Computational Scientist Thermal Engineer NASA Intern NSF Fellow Lecturer.

Updated on September 18, 2022

Comments

  • Paul
    Paul almost 2 years

    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?

    • Admin
      Admin over 12 years
      How about adding the alias to .bash_aliases ? Also how about aliasing the absolute path instead of relative path like alias petsc='/home/user/petsc-3.2-p6/petsc-arch/bin/mpiexec'
    • Admin
      Admin over 5 years
    • Admin
      Admin over 4 years
      I actually just used a system link which worked for me like: ln -sf /usr/bin/podman .local/bin/docker
  • Paul
    Paul over 12 years
    Your suggestion 2) works, but I want to be able to use the same command in multiple shell scripts without having to write the first line petsc="...". Is there a way to do this?
  • Panther
    Panther over 12 years
    Sounds as if you should put the command in a more standard location, such as /usr/local/bin
  • Paul
    Paul over 12 years
    That almost works... the only problem is that I need to be able to pass different flags to the executable "mpiexec"... For instance, I need to be able to execute something like "petsc -n 40 myexecutable" with the alias "petsc"
  • Paul
    Paul over 12 years
    The reason why I can't put it into my $PATH is because I have another 'mpiexec' file in another directory that is alredy in my $PATH. If I add the path to this new 'mpiexec', it will probably try to execute both of them... wouldn't it?
  • enzotib
    enzotib over 12 years
    @Paul: I added "$@" just to handle arguments.
  • enzotib
    enzotib over 12 years
    Cannot understand why not simply use "$@".
  • unhammer
    unhammer over 12 years
    Paul, it'll try to execute the one that's first in the PATH, not both.
  • unhammer
    unhammer over 12 years
    enzotib, ah I misread the way mpiexec was called, I thought it needed all args as one. Will edit my answer :)
  • pabouk - Ukraine stay strong
    pabouk - Ukraine stay strong over 9 years
    In the point 2 you do not set an alias but a variable.
  • valid
    valid over 9 years
    Not asked for by OP but relevant to the question title: Point 2 won't work with commands containing |. Here, use shopt -s expand_aliases & local alias, e.g. alias myalias='echo abc|rev' - requires line-break before use (see ALIASES in man bash). Point 4: Sourced file may prevent non-interactive execution, i.e. in a script. Look for early exit or return, e.g. [ -z "$PS1" ] && return (checks if primary prompt isn't set indicating non-interactive shell) or there may be a check for i in $- ($- contains shell options, i means interactive). See man bash for those variables.
  • Greenonline
    Greenonline about 9 years
    I like this solution, I will give it a try later
  • Eliah Kagan
    Eliah Kagan over 7 years
    @DavidFoerster This method works fine. Sourcing a script with the . or source buiiltin causes the current shell to execute all the commands in it. If alias expansion would occur in the shell in which . or source is run, it occurs. However, it's important to realize that this method is only sometimes useful, because often one needs or wants to execute a script in its own shell, with its own environment. Shell scripts written with the intention of being executed in the usual way should not usually be sourced instead--they often won't work right.
  • David Foerster
    David Foerster over 7 years
    @EliahKagan: Thanks. Now I understand what the answer is supposed to mean. I'll add an explanation.
  • muru
    muru over 7 years
    .bashrc is also read during non-interactive SSH command execution (that's why it has a check for interactivity at the top)
  • m3nda
    m3nda almost 7 years
    Altough aliases are deprecated in favor of shell functions, this answer os the only one which should be accepted. Even the old Debian 8 has version 4 of bash, so the ${BASH_ALIASES[alias]} is a nice option. Otherwise i had to edit lot of lines of my .bash_aliases to apply other things. Thank you.
  • Mikhail Lisakov
    Mikhail Lisakov about 4 years
    Indeed. In my case, it worked like this: eval ${BASH_ALIASES[foo]} . Even managed to get through nested aliasing, e.g. foo->foo123->/smth/real
  • ishahak
    ishahak almost 4 years
    I liked option 4. It allowed me to declare and use alias commands within my script
  • Ding-Yi Chen
    Ding-Yi Chen almost 4 years
    One of the exception is return. Say, you are writing a script that work for both as sourced or standalone, and you want to use quit to exit that script. Function like this cannot quit in sourced scritpt: quit(){ return $1 ;} Instead, you need to use alias: alias quit=return
  • Alex
    Alex over 3 years
    In case of 4, it is probably better to use .bash_aliases file instead of .bashrc. Then, only aliases can be sourced.
  • Fabian Röling
    Fabian Röling over 3 years
    I tried to use #4, but it didn't work. Alias in .bashrc: alias sed="sed -E" Script starts with the two lines from #4, then uses sed, but Regexes with + still do not work in it. Is this somehow specific to Ubuntu (if yes, why)? I'm using Manjaro.
  • maxwell
    maxwell about 3 years
    Yes. This is the right answer. Makes aliases work inside scripts whether invoked from prompt or cron. Thank you.
  • Timo
    Timo about 3 years
    According to man bash: ` If the -f option is given, the names refer to functions.`
  • StayCool
    StayCool almost 3 years
    It worked in Git Bash on Win 10. Thanks!
  • Oliver
    Oliver over 2 years
    Answer askubuntu.com/a/1057079/738406 is the correct answer, you have to use shopt -s expand_aliases
  • Admin
    Admin about 2 years
    This doesn't answer the question: how to use alias in a script. Workarounds are not useful for everyone else looking for solutions to the question as asked for various reasons and not trying to solve OP's exact problem.
  • Admin
    Admin about 2 years
    This only works for aliases created in the script. Aliases that were present on the system are still ignored; and those are the useful aliases.
  • Admin
    Admin about 2 years
    Aliases are not present "in the system". They are present in a given shell process. There is no way for a shell process to transmit its aliases to a child process. The login shell sources several files from /etc (the only one I remember is /etc/profile), in addition to .profile and .bashrc. If you source the same files in your script, you'll have those aliases too.