本文共 1051 字,大约阅读时间需要 3 分钟。
在使用Shell脚本时,确保脚本能够正常执行需要注意以下几点:
脚本可执行性
#!/bin/bash或#!/sh),需要预先为脚本文件赋予可执行权限。可以使用以下命令:chmod u+x script-name
或者使用更宽松的权限设置:
chmod 755 script-name
bash script-name # 或 sh script-name./script-name # 前提是脚本所在目录是当前工作目录
使用source或.执行脚本
source script-name 或 . script-name 可将脚本的函数和变量环境传递给当前的shell环境。source test.sh # 或 . test.sh
source和.的兼容性。source支持所有Bash脚本,而.仅适用于Bash脚本。理解不同执行方式
source和./script.sh之间的区别。bash script.sh和sh script.sh之间的差异。在实际应用中,特别是在需要长时间运行脚本的情况下,将脚本后台执行可以节省资源,并允许继续使用终端。
使用nohup
nohup可以将输出重定向到文件,并在后台运行脚本。nohup sh test.sh > out.txt &
out.txt 为输出日志文件。直接使用sh
sh命令将脚本后台运行并重定向输出。sh test.sh > & out.txt &
| 功能 | 用途 |
|---|---|
| sh脚本 | 将脚本后台执行 |
| Ctrl + c | 停止当前脚本任务 |
| Ctrl + z | 暂停当前脚本任务 |
| bg | 将当前脚本后台执行 |
| fg | 将当前脚本前台执行 |
转载地址:http://fgvd.baihongyu.com/