在Linux系统中执行.sh(Shell脚本)文件有多种方法,以下是详细步骤和注意事项:
bash script.sh
或
sh script.sh
bash、sh、zsh等)运行。bash比sh功能更丰富)。bash
chmod +x script.shbash
./script.shbash
/path/to/script.sh- 关键点:
- 必须使用./或绝对路径,否则系统会在$PATH环境变量中查找(通常找不到当前目录的脚本)。
- 如果脚本首行包含Shebang(如#!/bin/bash),系统会自动使用指定解释器执行。
.执行source script.sh
或
. script.sh
~/.bashrc)。权限不足错误:
-bash: ./script.sh: Permission denied
解决:运行chmod +x script.sh。
命令未找到错误:
bash: ./script.sh: No such file or directory
可能原因:
\r\n),需转换为Unix格式:
bash
dos2unix script.sh # 或运行 sed -i 's/\r$//' script.shShebang问题:
#!/bin/bash但系统无bash,可改为#!/bin/sh或安装对应解释器。-x参数查看执行过程:
bash
bash -x script.shbash
bash -n script.sh通过以上方法,你可以灵活地在Linux系统中运行.sh脚本。根据需求选择合适的方式即可!