简体   繁体   English

来自bash脚本的.bashrc源

[英]Source .bashrc from bash script

I'm trying to make a bash script to pipe a new alias to .bash_aliases and then source .bashrc: 我正在尝试制作一个bash脚本,以将新的别名传递给.bash_aliases,然后提供.bashrc的源:

#!/bin/sh
FIRST=$1
SECOND=${2:-cd `pwd`}

if [ -z $1 ]
then
    cat ~/.bash_aliases # no arg, show aliases
else
    echo alias $FIRST="'$SECOND'" >> ~/.bash_aliases
    . /home/andreas/.bashrc
fi

The . /home/andreas/.bashrc . /home/andreas/.bashrc . /home/andreas/.bashrc part doesn't work. . /home/andreas/.bashrc部分不起作用。

Following this I've tried running the script this way source . ./myscript 之后,我尝试以这种方式运行脚本source . ./myscript . ./myscript . . ./myscript

And following this I've tried adding PS1='foobar' to the script before the . /home/andreas/.bashrc 而下面这个我已经试过加入PS1='foobar'之前的脚本. /home/andreas/.bashrc . /home/andreas/.bashrc line. . /home/andreas/.bashrc行。

Neither works. 都不行。

When you say "doesn't work", I assume you mean that it doesn't actually put the alias in your interactive shell. 当您说“不起作用”时,我认为您的意思是实际上并未将别名放入您的交互式外壳中。 That's because this script runs in a subshell. 这是因为此脚本在子Shell中运行。 When you source .bashrc, it installs the aliases in the subshell. 当您获取.bashrc时,它将在别名中安装别名。 Then the subshell exits, and you return to your interactive shell. 然后,该子外壳程序退出,然后您返回到交互式外壳程序。 There is no way to modify the environment of a parent shell from a subshell. 无法从子外壳修改父外壳的环境。

That said, if this code ran from a function in your parent shell, instead of in a subshell, you'd be all set. 就是说,如果这段代码是从您的父外壳程序(而不是子外壳程序)中的函数运行的,那么您将大功告成。 Put this function in your .bashrc 将此功能放在您的.bashrc中

function addalias
{
    FIRST="$1"
    shift
    SECOND="$@"

    if [ "${FIRST}" == "" ]
    then
        cat ~/.bash_aliases
    else
        echo alias "$FIRST"="$SECOND" >> ~/.bash_aliases
        alias "$FIRST"="$SECOND"
    fi
}

That's because you are running this script in a separate shell process. 那是因为您在单独的 Shell进程中运行此脚本。 The . . command does work, but then the script exits and your current shell has not been altered at all. 该命令确实起作用,但是脚本退出并且您的当前shell完全没有被更改。

Put this script into a function in your ~/.bash_aliases file. 将此脚本放入〜/ .bash_aliases文件中的函数中。 That way your current shell will be updated. 这样,您当前的外壳将被更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM