linux执行shell文件中的命令
linux执行shell文件中的命令详细介绍
在 Linux 系统里,执行 shell 文件中的命令,一般有以下几种常见的方式。
1. 赋予执行权限并直接运行
首先要给 shell 文件赋予执行权限,然后直接运行该文件。以下是具体步骤和示例代码:
bash
+x your_script.sh
./your_script.sh
在上述代码里,chmod +x 这个命令用于给 your_script.sh 文件添加执行权限,./ 则表示在当前目录下执行该脚本。
2. 使用
sh 或
bash 命令执行
不赋予文件执行权限,也能借助 sh 或者 bash 命令来执行 shell 文件。示例如下:
bash
your_script.shyour_script.sh
3. 使用
source 命令执行
source 命令(也可以用 . 替代)能够在当前 shell 环境里执行脚本文件,而不是开启一个新的子 shell。示例如下:
bash
your_script.shyour_script.sh
使用 source 命令执行脚本时,脚本里定义的变量和函数会在当前 shell 环境中生效。
完整示例
假设你有一个名为 test.sh 的 shell 脚本,内容如下:
bash
下面是执行这个脚本的完整示例:
bash
test.sh
#!/bin/bash
echo "Hello, World!"
EOF
+x test.sh
./test.sh
test.sh
test.sh
9912345678910111213141516
+x test.sh./test.sh
test.sh
test.sh
上述三种方式都能执行 shell 文件中的命令,你可以依据实际需求进行选择。