How to use aliases defined in .bashrc in other scripts?

后端 未结 6 956
情话喂你
情话喂你 2020-11-27 06:36

In ~/.bashrc, I defined some aliases. But I cannot use them in other shell scripts, where I can only use aliases defined right there. Even though I sourced bashrc, it still

相关标签:
6条回答
  • 2020-11-27 07:24

    The simplest answer is to do the 2 important things or it wont' work.

    #!/bin/bash -i
    
    # Expand aliases defined in the shell ~/.bashrc
    shopt -s expand_aliases
    

    After this, your aliases that you have defined in ~/.bashrc they will be available in your shell script (giga.sh or any.sh) and to any function or child shell within such script.

    If you don't do that, you'll get an error:

    your_cool_alias: command not found
    
    0 讨论(0)
  • 2020-11-27 07:24

    .bashrc is meant for one purpose: to configure the environment for your interactive shells. If you have code that you want shared between your .bashrc and other scripts, then it belongs in a separate file that is sourced by each of your .bashrc and shell script.

    0 讨论(0)
  • 2020-11-27 07:27

    There is a way of doing it globally without adding lines to each script you execute: by using the BASH_ENV variable.

    Here is my setup for OS X 10.8.5:

    /etc/launchd.conf:

    setenv BASH_ENV /Users/DK/.env
    

    ~/.bash_profile:

    # == Bash setup for interactive shells ==    
    # === Environment for all shells ===
    . $BASH_ENV    
    # [skipped]
    

    ~/.env:

    # == Setup for all shells ==
    # This is executed for all interactive and for non-interactive shells (e.g. scripts)
    
    shopt -s expand_aliases extglob xpg_echo
    
    # [skipped] Misc. variables and PATH setup
    
    # === General aliases ===
    
    alias pause='echo "Press [Return] or [Enter] to continue..."; read' # read -p does not display prompt in Eclipse console
    
    # [skipped]
    
    0 讨论(0)
  • 2020-11-27 07:29

    I had this problem and I reloaded the file with this command to fix it.

    $ source ~/.bashrc 
    
    0 讨论(0)
  • 2020-11-27 07:30

    You need to do shopt -s expand_aliases in the script in addition to sourcing ~/.bashrc.

    0 讨论(0)
  • 2020-11-27 07:34

    Stolen from enzotib on ask ubuntu: Alias are deprecated in favor of shell functions. From 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 scripts.

    0 讨论(0)
提交回复
热议问题