bash 在 .bash_profile 中创建运行 shell 脚本的别名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22641590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:01:22  来源:igfitidea点击:

Creating aliases in .bash_profile that run a shell script

bashshell.bash-profile

提问by user2656127

So I have a script called spotlyrics.sh that I want to be able to run using the command "lyrics" in the terminal.

所以我有一个名为 spotlyrics.sh 的脚本,我希望能够在终端中使用“lyrics”命令运行它。

I have opened up my .bash_profile and am wondering how I can create the alis which 1) finds the script and then 2) executes it

我打开了我的 .bash_profile 并且想知道如何创建 alis 1) 找到脚本然后 2) 执行它

The file is inside a folder called bashat the following path

该文件位于名为bash以下路径的文件夹中

/Users/username/Documents/bash

What I have so far (inside my bash profile), which doesn't work because I guess it's not "executing" the script.

到目前为止我所拥有的(在我的 bash 配置文件中),这不起作用,因为我猜它不是“执行”脚本。

alias spotlyrics=“/Users/username/Documents/bash/spotlyrics.sh“

I get the following error when running "spotlyrics" in the terminal:

在终端中运行“spotlyrics”时出现以下错误:

-bash: “/Users/username/Documents/bash/spotlyrics.sh“: No such file or directory

Would love some help, thanks!

希望得到一些帮助,谢谢!

回答by

You've been editing your .bash_profilewith something that is not a proper text editor. The quotation marks are not ASCII, and therefore not actually quotation marks as far as the shell is concerned.

您一直在.bash_profile使用不合适的文本编辑器进行编辑。引号不是 ASCII,因此就 shell 而言实际上不是引号。

回答by Sumanth K gowda

Well, the shell scripts are not executable by just calling it's name, they should be run using "source" command(in case of not c-shell, dot command(.)can also be used).So while adding an alias in .bashrc or .bash_profile for running a shell script append source command before the path to the shell script. In your case probably this should work:`

好吧,shell 脚本不能通过调用它的名字来执行,它们应该使用“”命令运行(如果不是 c-shell,也可以使用dot 命令(.))。因此,在 .用于运行 shell 脚本的 bashrc 或 .bash_profile 在 shell 脚本的路径之前追加源命令。在您的情况下,这可能应该有效:`

alias spotlyrics='source /Users/username/Documents/bash/spotlyrics.sh'`

Please let me know if it doesn't work. Because it worked for me.

如果它不起作用,请告诉我。因为它对我有用。

回答by kojiro

Instead of beating around the bush with aliasing a script to a name it mostly already has, why not put the script in a directory in PATH and let it be its own command?

与其绕圈子给脚本取一个它已经拥有的别名,为什么不把脚本放在 PATH 中的一个目录中,让它成为它自己的命令呢?

mkdir ~/bin
echo 'PATH+=:$HOME/bin' >> ~/.bashrc
mv "/path/to/spotlyrics.sh" ~/bin/spotlyrics && chmod +x ~/bin/spotlyrics

Then restart the shell (log out and back in) and you won't need the alias.

然后重新启动外壳程序(注销并重新登录),您将不需要别名。