我知道它,忘记它,重新学习它。是时候写下来了。


要启动shell脚本'file.sh':

sh file.sh

bash file.sh

另一个选项是使用chmod命令设置可执行权限:

chmod +x file.sh

现在运行.sh文件,如下所示:

./file.sh

对于伯恩壳:

sh myscript.sh

bash的:

bash myscript.sh

运行一个不可执行的sh脚本,使用:

sh myscript

要运行一个不可执行的bash脚本,使用:

bash myscript

启动一个可执行文件(任何具有可执行权限的文件);你只需要通过路径来指定它:

/foo/bar
/bin/bar
./bar

要使一个脚本可执行,给它必要的权限:

chmod +x bar
./bar

当一个文件是可执行的,内核负责找出如何执行它。对于非二进制文件,可以通过查看文件的第一行来完成。它应该包含一个hashbang:

#! /usr/bin/env bash

散列告诉内核要运行什么程序(在本例中,命令/usr/bin/env使用参数bash运行)。然后,脚本被传递给程序(作为第二个参数),同时传递给脚本的所有参数作为后续参数。

That means every script that is executable should have a hashbang. If it doesn't, you're not telling the kernel what it is, and therefore the kernel doesn't know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user's default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash).

关于/usr/bin/env的说明

最常见的是,你会看到这样的散列:

#!/bin/bash

结果是,内核将运行程序/bin/bash来解释脚本。不幸的是,bash并不总是默认提供的,并且它并不总是在/bin中可用。虽然在Linux机器上通常是这样,但在其他一系列POSIX机器上,bash发布在不同的位置,例如/usr/xpg/bin/bash或/usr/local/bin/bash

因此,要编写可移植的bash脚本,我们不能依赖于对bash程序的位置进行硬编码。POSIX已经有了一种处理这种情况的机制:PATH。其思想是,您将程序安装在PATH中的一个目录中,当您想按名称运行程序时,系统应该能够找到您的程序。

遗憾的是,你不能这样做:

#!bash

内核不会(有些可能)为您执行PATH搜索。有一个程序可以帮你做PATH搜索,它叫env。幸运的是,几乎所有系统都在/usr/bin中安装了env程序。所以我们使用一个硬编码的路径启动env,然后对bash进行path搜索并运行它,这样它就可以解释你的脚本:

#!/usr/bin/env bash

这种方法有一个缺点:根据POSIX, hashbang可以有一个参数。在本例中,我们使用bash作为env程序的参数。这意味着我们没有空间来传递参数给bash。所以没有办法转换像#!/bin/bash -exu。您必须将set -exu放在hashbang之后。

This approach also has another advantage: Some systems may ship with a /bin/bash, but the user may not like it, may find it's buggy or outdated, and may have installed his own bash somewhere else. This is often the case on OS X (Macs) where Apple ships an outdated /bin/bash and users install an up-to-date /usr/local/bin/bash using something like Homebrew. When you use the env approach which does a PATH search, you take the user's preference into account and use his preferred bash over the one his system shipped with.


如果你想让脚本在当前shell中运行(例如,你想让它能够影响你的目录或环境),你应该说:

. /path/to/script.sh

or

source /path/to/script.sh

例如,注意/path/to/script.sh可以是相对的。Bin /script.sh运行当前目录下Bin目录下的script.sh。


首先,给予执行许可:- Chmod +x script_name

如果脚本不可执行:- 运行sh脚本文件:- sh script_name 运行bash脚本文件:- bash script_name 如果脚本可执行:- 。/ script_name

注意:你可以使用'ls -a'来检查文件是否可执行。


文件扩展名.命令被分配给Terminal.app。双击任何.command文件将执行它。


添加一点,在同一个文件夹中运行解释器,仍然使用#!脚本中的Hashbang。

例如,从/usr/bin复制的php7.2可执行文件位于一个文件夹中,该文件夹中有一个hello脚本。

#!./php7.2
<?php

echo "Hello!"; 

运行它:

./hello

它们的行为是一样的:

./php7.2 hello

具有良好文档的适当解决方案可以是linuxdeploy和/或appimage工具,这是在底层使用这种方法。