简体   繁体   English

如何在bash脚本(Ubuntu 17.04)中正确设置别名?

[英]How do I properly set aliases in a bash script (Ubuntu 17.04)?

I have this script called menal in my ~/bin directory: 我的~/bin目录中有一个名为menal脚本:

#!/bin/sh

alias mendir='cd ~/projects/myproject'

It has executable property and I expect that when I run it it sets an appropiate alias for cd command for the terminal session. 它具有可执行文件属性,我希望在运行它时为终端会话的cd命令设置适当的别名。 But it doesn't. 但事实并非如此。 When I type $ menal in terminal it shows no error, but when I try $ mendir after that I get 当我在终端中输入$ menal ,它没有显示任何错误,但是当我尝试输入$ mendir之后,我得到了

No command 'mendir' found, did you mean:
 Command 'menhir' from package 'menhir' (universe)
mendir: command not found

When I type 当我打字

$ alias mendir='cd ~/projects/myproject'
$ mendir

in terminal, it works. 在终端,它的工作原理。

What am I doing wrong? 我究竟做错了什么? Is it a script scope issue or something? 是脚本作用域问题还是什么?

Yes, it's a scope problem. 是的,这是一个范围问题。 Calling it the following way won't produce the result you expect: 通过以下方式调用它不会产生您期望的结果:

./bin/menal

If you want the alias to persist, use source : 如果要保留别名,请使用source

source ./bin/menal

You can add it to your .bash_profile . 您可以将其添加到.bash_profile

alias mendir='cd ~/projects/myproject'

then do source ~/.bash_profile 然后做source ~/.bash_profile

It should create the alias and also will work on every login. 它应该创建别名,并且也可以在每次登录时使用。

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

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