简体   繁体   English

来自脚本的源bashrc失败

[英]Source bashrc from script failing

I've written a simple bash script that adds an alias to my .bashrc automatically, and when it finishes, I would like it to source the .bashrc 我写了一个简单的bash脚本,自动为我的.bashrc添加一个别名,当它完成时,我希望它能找到.bashrc

It works fine as of now, for example 例如,它现在工作正常

./addalias.sh ls 'ls -l' 

properly appends 'alias ls='ls -l' to the .bashrc, but doesn't source it. 正确地将'alias ls ='ls -l'附加到.bashrc,但不会将其获取。

The code is as follows: 代码如下:

#!/bin/bash
FIRST=$1

SECOND=${2:-cd `pwd`}

echo alias $FIRST="'$SECOND'" >> /home/oscar/.bashrc
echo alias $FIRST="'$SECOND'"

source /home/oscar/.bashrc

That doesn't work, nor does running an alias ("sourcebash") to source the bash instead of the last line. 这不起作用,也没有运行别名(“sourcebash”)来获取bash而不是最后一行。

Any thoughts on how this could be fixed? 有关如何解决这个问题的任何想法?

The shell that runs 'addalias.sh' does source the .bashrc file; 运行'addalias.sh'的shell确实获取.bashrc文件; it then exits. 它然后退出。 It does not and cannot affect the parent shell's environment. 它不会也不会影响父shell的环境。

You'd have to invoke the command as: 你必须调用命令:

source ./addalias.sh ls 'ls --color=auto'

Or: 要么:

. ./addalias.sh ls 'ls --color=auto'

( Now fixed: And I'm not convinced that, even in a question, playing with sudo rm -fr /* is remotely sensible. There's too much risk of an idiot copying and not realizing.) 现在已经修好了:我不相信,即使是在一个问题上,玩sudo rm -fr /*也是非常明智的。有一个白痴复制的风险太大而且没有意识到。)

Maybe you can make it a function or an alias instead of a bash script. 也许你可以把它变成一个函数或别名而不是一个bash脚本。 Doing that might cause the changes to occur in the same shell. 这样做可能会导致更改发生在同一个shell中。

i'd make an alias which calls this 'addalias' script, then sources the newly-modified file. 我会创建一个别名来调用这个'addalias'脚本,然后获取新修改的文​​件。

something like 就像是

alias really_add_alias="addalias.sh; . .bashrc"

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

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