我有一个shell脚本,我想在不使用“sh”或“bash”命令的情况下运行。例如:
而不是:sh script.sh
我想使用:script.sh
我该怎么做呢?
P.S. (i)我不太使用shell脚本,我试着阅读关于别名的内容,但我不知道如何使用它们。
(ii)我还读了关于将脚本链接到PATH变量中的另一个文件。我正在使用我的大学服务器,我没有权限在这些位置创建文件。
我有一个shell脚本,我想在不使用“sh”或“bash”命令的情况下运行。例如:
而不是:sh script.sh
我想使用:script.sh
我该怎么做呢?
P.S. (i)我不太使用shell脚本,我试着阅读关于别名的内容,但我不知道如何使用它们。
(ii)我还读了关于将脚本链接到PATH变量中的另一个文件。我正在使用我的大学服务器,我没有权限在这些位置创建文件。
当前回答
在本例中,文件名为myShell
首先,我们需要创建这个文件,我们可以输入以下内容:
sudo nano myShell
注意到没有。sh扩展名了吗? 这是因为当我们从终端运行它时,我们只需要键入myShell来运行我们的命令!
现在,在nano的顶部行必须是#!/bin/bash,然后在继续之前留下新行。
为了演示,我将添加一个基本的Hello World!响应
所以,我输入以下内容:
echo Hello World!
之后,我的例子应该是这样的:
#!/bin/bash
echo Hello World!
现在保存文件,然后运行这个命令:
chmod +x myShell
现在我们已经使文件可执行,我们可以使用以下命令将其移动到/usr/bin/:
sudo cp myShell /usr/bin/
恭喜!我们的命令现在完成了!在终端中,我们可以输入myShell,它应该说Hello World!
其他回答
添加。(当前目录)到您的PATH变量。 你可以通过编辑你的.profile文件来做到这一点。 在.profile文件中放入以下一行 = $ PATH:。 只需确保在脚本的开头添加Shebang (#!/bin/bash)行,并使脚本可执行(使用chmod +x <文件名>)。
这些是直接使用脚本名称的先决条件:
在最顶部添加shebang行(#!/bin/bash)。 使用chmod u+x scriptname使脚本可执行(其中scriptname是脚本的名称)。 将脚本放在/usr/local/bin文件夹下。 注意:我建议将它放在/usr/local/bin下,因为很可能该路径已经添加到path变量中。 只使用脚本名称scriptname运行脚本。
如果你没有访问/usr/local/bin的权限,那么执行以下操作:
Create a folder in your home directory and call it bin. Do ls -lA on your home directory, to identify the start-up script your shell is using. It should be either .profile or .bashrc. Once you have identified the start up script, add the following line: PATH="$PATH:$HOME/bin" Once added, source your start-up script or log out and log back in. To source, put . followed by a space and then your start-up script name, e.g. . .profile or . .bashrc Run the script using just its name, scriptname.
你可以输入sudo install(脚本的名称)/usr/local/bin/(你想输入什么来执行脚本)
例如:sudo install quickcommit.sh /usr/local/bin/quickcommit 输入密码
现在不需要.sh就可以在任何目录下运行
通过使用文件的属性使脚本文件成为可执行文件 在~/.bashrc中为可执行文件创建别名。别名<别名> = <完整脚本文件路径>' 刷新用户会话以应用它。源~ / . bashrc
在文件顶部添加一个“shebang”:
#!/bin/bash
并使您的文件可执行(chmod +x script.sh)。
最后,修改路径以添加脚本所在的目录:
export PATH=$PATH:/appropriate/directory
(通常,你需要$HOME/bin来存储你自己的脚本)