在Linux系统中执行.sh(Shell脚本)文件有多种方法,以下是详细步骤和注意事项:
bash script.sh
或
sh script.sh
bash
、sh
、zsh
等)运行。bash
比sh
功能更丰富)。bash
chmod +x script.sh
bash
./script.sh
bash
/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.sh
Shebang问题:
#!/bin/bash
但系统无bash
,可改为#!/bin/sh
或安装对应解释器。-x
参数查看执行过程:
bash
bash -x script.sh
bash
bash -n script.sh
通过以上方法,你可以灵活地在Linux系统中运行.sh脚本。根据需求选择合适的方式即可!