在 Linux 中执行 `.sh` 文件的方法有多种,具体方法如下:
---
方法 1:使用 `bash` 或 `sh` 命令
最直接的方法是使用 `bash` 或 `sh` 运行脚本:
```bash
bash script.sh
# 或者
sh script.sh
```
这种方法不要求脚本具有可执行权限。
---
方法 2:赋予可执行权限并直接运行
如果希望直接运行脚本,需要先赋予其可执行权限:
```bash
chmod +x script.sh
./script.sh
```
其中:
- `chmod +x script.sh` 赋予执行权限
- `./script.sh` 直接运行脚本
---
方法 3:指定解释器运行
如果 `.sh` 文件的第一行包含 Shebang(如 `#!/bin/bash`),可以这样执行:
```bash
./script.sh
```
确保 `script.sh` 第一行是:
```bash
#!/bin/bash
```
或:
```bash
#!/bin/sh
```
系统会自动使用指定的解释器(`/bin/bash` 或 `/bin/sh`)运行脚本。
---
方法 4:在当前 shell 中运行(source 执行)
如果不想启动新进程,而是在当前 shell 运行脚本,可以用 `source` 或 `.` 命令:
```bash
source script.sh
# 或者
. script.sh
```
这种方式适用于修改当前 shell 环境的脚本,例如修改环境变量等。
---
方法 5:通过 `cron` 或 `systemd` 定时执行
如果要定期执行 `.sh` 脚本,可以使用 `cron` 或 `systemd` 计划任务:
```bash
crontab -e
```
然后添加:
```
0 5 * * * /path/to/script.sh
```
表示每天凌晨 5 点执行 `script.sh`。
---
方法 6:在后台运行
如果想让脚本在后台运行,可以使用:
```bash
nohup ./script.sh &
# 或者
./script.sh &
```
这样脚本会在后台运行,即使关闭终端也不会终止。
---
如果 `.sh` 文件无法运行,可以检查:
1. 文件格式是否正确(确保是 UNIX 格式,可用 `dos2unix script.sh` 转换)。
2. 是否有执行权限(使用 `chmod +x`)。
3. 是否指定了解释器(`#!/bin/bash` 或 `#!/bin/sh`)。
4. 是否有必要的依赖(检查 `which bash` 或 `which sh`)。
这样,你就可以顺利执行 Linux 的 `.sh` 文件了!