shell脚本实现传参
时间: 2023-03-27 07:03:47 浏览: 61
可以使用$1、$2、$3等变量来获取传入的参数,例如:
#!/bin/bash
echo "第一个参数为:$1"
echo "第二个参数为:$2"
echo "第三个参数为:$3"
然后在命令行中执行脚本并传入参数,例如:
./test.sh 1 2 3
输出结果为:
第一个参数为:1
第二个参数为:2
第三个参数为:3
相关问题
shell脚本+传参执行
以下是使用Python执行shell脚本并动态传参的示例:
```python
import subprocess
# 定义shell脚本命令和参数
cmd = 'sh my_script.sh'
arg1 = 'arg1_value'
arg2 = 'arg2_value'
# 将参数添加到命令中
cmd_with_args = f'{cmd} {arg1} {arg2}'
# 执行shell脚本命令
result = subprocess.run(cmd_with_args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 输出结果
print(result.stdout.decode('utf-8'))
```
在上面的示例中,我们首先定义了要执行的shell脚本命令和参数。然后,我们将参数添加到命令中,并使用`subprocess.run()`函数执行该命令。最后,我们将输出结果打印到控制台上。
需要注意的是,`subprocess.run()`函数的`shell`参数必须设置为`True`,以便能够执行shell命令。另外,我们使用`stdout=subprocess.PIPE`和`stderr=subprocess.PIPE`参数来捕获命令的输出结果。
shell脚本函数传参
Shell脚本函数传参方式与传统的编程语言中的函数传参方式类似,即在函数调用时将参数列表放在圆括号中并在函数定义中使用 $1,$2,$3等来获取参数。 例如:
```
#!/bin/bash
function test_func {
echo "The first parameter is $1"
echo "The second parameter is $2"
echo "All parameters are $@"
}
test_func "Hello" "World"
```
输出:
```
The first parameter is Hello
The second parameter is World
All parameters are Hello World
```