子shell/子进程中的别名

lis*_*sak 22 linux shell alias

我在 /etc/profile.d/alias.sh 中为每个登录 shell 设置了别名。但是如果我运行 script.sh,我就不能使用那个别名。如何为子shell或子进程设置别名?

/etc/profile.d/alias.sh

alias rmvr='rm -rv';
alias cprv='cp -rv';
alias mvrv='mv -rv';
Run Code Online (Sandbox Code Playgroud)

jw0*_*013 26

别名不会被继承。这就是为什么它们传统上设置在bashrc而不是profile. 而是script.sh从您的.bashrc或系统范围内的源中获取。

  • 我不认为 .bashrc 有帮助......如果你在子shell中使用那个别名,它不知道 (2认同)

Dro*_*roj 23

如果您希望它们被继承到子 shell,请改用函数。这些可以导出到环境 ( export -f),然后子 shell 将定义这些函数。

因此,对于您的示例之一:

rmvr() { rm -rv "$@"; }
export -f rmvr
Run Code Online (Sandbox Code Playgroud)

如果你有一堆,那么先设置导出:

set -a # export the following funcs
rmvr() { rm -rv "$@"; }
cpvr() { cp -rv "$@"; }
mvrv() { mv -rv "$@"; }
set +a # stop exporting
Run Code Online (Sandbox Code Playgroud)

  • 这非常有用,可以解决我的问题。 (4认同)

小智 11

这是因为 /etc/profile.d/ 仅由交互式登录 shell 使用。但是,/etc/bash.bashrc由交互式非登录外壳使用。

由于我通常会为系统设置一些全局别名,因此我已经开始创建/etc/bashrc.d可以放置具有一些全局别名的文件的位置:

    HAVE_BASHRC_D=`cat /etc/bash.bashrc | grep -F '/etc/bashrc.d' | wc -l`

    if [ ! -d /etc/bashrc.d ]; then
            mkdir -p /etc/bashrc.d
    fi
    if [ "$HAVE_BASHRC_D" == "0" ]; then
        echo "Setting up bash aliases"
            (cat <<-'EOF'
                                    if [ -d /etc/bashrc.d ]; then
                                      for i in /etc/bashrc.d/*.sh; do
                                        if [ -r $i ]; then
                                          . $i
                                        fi
                                      done
                                      unset i
                                    fi
                            EOF
            ) >> /etc/bash.bashrc

    fi
Run Code Online (Sandbox Code Playgroud)