如何制作“宏”以在 OS X 终端中自动执行一些 bash 命令?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20014920/
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
How to make a "macro" to automate some bash commands in OS X Terminal?
提问by iMatthewCM
I'm pretty decent with bash and UNIX commands, and the Terminal app, but I'm wondering, is there a way to make a "macro" (maybe that's the wrong word!) to automate some tasks?
我很擅长使用 bash 和 UNIX 命令以及终端应用程序,但我想知道,有没有办法制作“宏”(也许这是错误的词!)来自动执行某些任务?
For example, to get into my current project directory, I type:
例如,要进入我当前的项目目录,我输入:
$ cd ~/Documents/College/F13/CS362/lab3/os-lab-3
And then I immediately do
然后我立即做
$ hg pull
(password)
(密码)
And then
进而
$ hg update
So is there a way to even automate that first step of the cd call? I've never tried anything like that before, not sure if what I'm going for is even possible.
那么有没有办法甚至自动化 cd 调用的第一步?我以前从未尝试过这样的事情,不确定我要做什么甚至可能。
Bonus: is there a way to have the macro enter my password when prompted as well? Security/privacy is not really an issue here, there's no thermonuclear codes hiding around in the repo.
奖励:有没有办法让宏在提示时输入我的密码?安全/隐私在这里并不是真正的问题,回购中没有隐藏的热核代码。
回答by gbeagle
The name generally used in this context (a macro in bash) is shell script. To automate the commands from your post you would need to create a file with a name like 'myscript.sh' with the following contents:
在此上下文中通常使用的名称(bash 中的宏)是shell script。要自动执行帖子中的命令,您需要创建一个名为“myscript.sh”的文件,其中包含以下内容:
#!/bin/bash
cd ~/Documents/College/F13/CS362/lab3/os-lab-3
hg pull
hg update
The first line of the script is a hashbang. This is a special comment line which indicates that file should be executed using the indicated program. Bash in this case.
脚本的第一行是hashbang。这是一个特殊的注释行,表示应该使用指定的程序执行文件。在这种情况下重击。
To run the script first ensure that it is executable by running the following command:
要运行脚本,首先通过运行以下命令确保它是可执行的:
chmod +x myscript.sh
From there in terminal window just run the script by specifying the path to it:
在终端窗口中,只需通过指定路径来运行脚本:
./myscript.sh
Don't put passwords into shell scripts though! It is a bad habit. For authentication with Mercurial an ssh key pair is the best way to go. The ssh key can be loaded into OSX's keychain, so you won't have to type anything when you run the script. You'll also need to add the public portion of your ssh key pair to the list of authorized hosts on the remote Mercurial repository.
但是不要将密码放入 shell 脚本中!这是一个坏习惯。对于使用 Mercurial 进行身份验证,最好的方法是使用 ssh 密钥对。ssh 密钥可以加载到 OSX 的钥匙串中,因此您在运行脚本时无需输入任何内容。您还需要将 ssh 密钥对的公共部分添加到远程 Mercurial 存储库上的授权主机列表中。