更新时间:2023-12-04 18:24:59
在shell中执行脚本有两种方法.根据您的需要,您将需要执行以下一项操作(不要同时执行!).
There are two ways of executing a script in the shell. Depending upon your needs, you will have to do one of the following (don't do both!).
要将脚本作为程序启动:
To launch the script as a program:
#!/bin/bash
添加为脚本的第一行#!/bin/bash
as the first line of the script这将由加载程序读取,加载程序具有特殊的逻辑,该逻辑将前两个字符#!
插入为启动下一个程序并将其内容传递给它".请注意,这仅适用于为接收内容而编写的程序
This will be read by the loader, which has special logic that interperts the first two characters #!
as "launch the program coming next, and pass the contents into it". Note this only properly works for programs written to receive the contents
要将脚本源到当前shell中:
To source the script into the current shell:
. script.sh
或source script.sh
注意:bash中的.
等同于bash中的source
.
Note: .
in bash is equivalent to source
in bash.
这就像您键入"script.sh"的内容一样.例如,如果您在"script.sh"中设置变量,则该变量将在当前shell中设置.您将需要取消定义变量以将其从当前shell中清除.
This acts as if you typed in the contents of "script.sh". For example, if you set a variable in "script.sh" then that variable will be set in the current shell. You will need to undefine the variable to clear it from the current shell.
这与#!/bin/bash
示例有很大的不同,因为在新的bash
子进程中设置变量不会影响您从中启动该子进程的shell.
This differs heavily from the #!/bin/bash
example, because setting a variable in the new bash
subprocess won't impact the shell you launched the subprocess from.