来自bash脚本的.bashrc源 [英] Source .bashrc from bash script

查看:100
本文介绍了来自bash脚本的.bashrc源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个bash脚本,以将新的别名传递给.bash_aliases,然后提供.bashrc的源代码:

I'm trying to make a bash script to pipe a new alias to .bash_aliases and then source .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

./home/andreas/.bashrc 部分无效.

之后,我尝试了通过源../myscript.

Following this I've tried running the script this way source . ./myscript.

然后按照,我尝试添加 PS1 ='foobar'之前的脚本./home/andreas/.bashrc 行.

And following this I've tried adding PS1='foobar' to the script before the . /home/andreas/.bashrc line.

都不行.

推荐答案

当您说不起作用"时,我想您的意思是它实际上并未将别名放入您的交互式外壳中.这是因为此脚本在子Shell中运行.当您获取.bashrc时,它将在别名中安装别名.然后,该子外壳程序退出,然后您返回到交互式外壳程序.无法从子外壳修改父外壳的环境.

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. When you source .bashrc, it installs the aliases in the subshell. 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.

也就是说,如果这段代码是从您的父外壳程序(而不是子外壳程序)中的函数运行的,那么您将大功告成.将此功能放在您的.bashrc

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

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

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

这篇关于来自bash脚本的.bashrc源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆