bashsh

How can i access aliases located inside my .bashrc file from another script


  • Here is the code in .bashrc
#!/bin/bash
alias py="python"
alias psv="python -m http.server"
alias cl="clear"
  • Here is the code in foo.sh
#!/bin/bash
git add .
git commit -m "fixed requests error"
git push
cl

I get the following at the end

command not found

Solution

  • Aliases are not expanded when the shell is not interactive (running in a script, for instance). From the man page:

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

    You'll have to add shopt -s expand_aliases and then source your .bashrc in your script before using them, but you should prefer using functions since they're more flexible, allowing you to group multiple commands and even add additional arguments.

    For what it's worth, the bash manual has this at the end of the aliases section:

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