shell脚本执行的3种方式
时间: 2023-04-27 15:05:00 浏览: 63
1. 直接在命令行中执行:将脚本文件作为参数传递给shell解释器,例如:`sh script.sh` 或 `./script.sh`(前提是脚本文件有可执行权限)。
2. 在脚本文件中添加shebang(#!/bin/bash)并赋予可执行权限,然后直接执行脚本文件,例如:`./script.sh`。
3. 将脚本文件作为参数传递给其他命令或程序,例如:`find . -name "*.sh" -exec sh {} \;`。
相关问题
shell脚本传参 3种方式
Shell脚本是一种命令行解释器,可以直接执行命令、操作文件等。在实际应用中,运行的Shell脚本往往需要传入参数来控制脚本的行为和逻辑,因此学会Shell脚本传参对于我们写出好的脚本是十分必要的。下面介绍Shell脚本传参的三种方式:
1. 位置参数传参: 通过$1、$2、$3...的变量获取传入的参数,其中$0表示脚本的名字。
例如:
```
#!/bin/bash
echo "The first parameter is $1 and the second parameter is $2."
```
执行:
```
./test.sh hello world
```
输出:
```
The first parameter is hello and the second parameter is world.
```
2. 特殊变量传参: Shell脚本还提供了一些特殊变量可以用来获取所传递参数的信息,如传递参数个数的${#}、所有参数组成的${*}和所有参数组成的${@}。
例如:
```
#!/bin/bash
echo "There are $# parameters."
echo "All parameters are ${*}."
echo "All parameters are ${@}."
```
执行:
```
./test.sh hello world 123
```
输出:
```
There are 3 parameters.
All parameters are hello world 123.
All parameters are hello world 123.
```
3. 命令行传参: 在执行Shell脚本时直接通过“sh test.sh 参数1 参数2…”的方式传参。这种方式需要注意空格和引号,可以使用双引号保留参数中的空格。
例如:
```
#!/bin/bash
echo "The first parameter is $1 and the second parameter is $2."
```
执行:
```
sh test.sh "hello world" 123
```
输出:
```
The first parameter is hello world and the second parameter is 123.
```
总结:以上三种方式是Shell脚本传参的常用方法,通过具体的需求来决定选用哪种方式,以达到最好的效果。
Linux五种方式执行Shell脚本文件
1. 给脚本文件添加可执行权限,并直接执行:
```
chmod +x script.sh
./script.sh
```
2. 使用bash解释器执行:
```
bash script.sh
```
3. 使用sh解释器执行:
```
sh script.sh
```
4. 使用source命令执行:
```
source script.sh
```
5. 使用.命令执行:
```
. script.sh
```
注意:第4和第5种方式不会启动子shell,而是在当前shell环境下执行脚本,因此可以在脚本中修改当前shell环境的变量。而其他三种方式则会在子shell中执行脚本,对当前shell环境无影响。