返回信息流最不会写shell,但是现在遇到一个问题,特来我邮求助。
问题是这样的,我的shell里面需要一堆变量,例如
port
user
host
registry
等等,至少10个
这个也就算了,我还有n个环境,dev test stage。。
我现在的写法是写死在脚本里面,用ifelse做判断
但是越来越多的时候就很垃圾,
所以想问一下有没有更好的放这些的地方,更好的把这个参数传进去,更好的使用,谢谢啦
啥都没有限制,求大神指点一二,谢谢啦
这是一条镜像帖。来源:北邮人论坛 / linux / #160985同步于 2023/6/19
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Linux机器人发帖
shell问题求助 - 如何设计传参
hanleirx
2023/6/19镜像同步23 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
为什么不问问神奇chatgpt呢
Q: how to pass parameters to shell scripts
A: To pass parameters to a shell script, you can use the "$1", "$2", "$3", etc. variables to refer to the first, second, third, and so on parameters passed to the script. For example, if you have a script called "myscript.sh" and you want to pass two parameters to it, you can run it like this:
```
./myscript.sh param1 param2
```
Inside the script, you can refer to the parameters using the "$1" and "$2" variables. For example:
```
#!/bin/bash
echo "The first parameter is: $1"
echo "The second parameter is: $2"
```
This will output:
```
The first parameter is: param1
The second parameter is: param2
```
Q: how to pass named parameters to shell scripts
A: In Bash, you can use the `getopts` command to parse named parameters passed to a shell script. Here's an example:
```
#!/bin/bash
while getopts ":a:b:" opt; do
case $opt in
a)
param_a="$OPTARG"
;;
b)
param_b="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
echo "Parameter a: $param_a"
echo "Parameter b: $param_b"
```
In this example, the `getopts` command is used to parse the named parameters `-a` and `-b`. The `while` loop iterates over each option passed to the script, and the `case` statement handles each option. The `OPTARG` variable contains the value of the option's argument.
You can run the script like this:
```
./myscript.sh -a value_a -b value_b
```
This will output:
```
Parameter a: value_a
Parameter b: value_b
```
If you pass an invalid option or an option without an argument, the script will output an error message and exit with a status code of 1.
【 在 sjw1996 的大作中提到: 】
: 为什么不问问神奇chatgpt呢
: Q: how to pass parameters to shell scripts
: A: To pass parameters to a shell script, you can use the "$1", "$2", "$3", etc. variables to refer to the first, second, third, and so on parameters passed to the script. For example, if you have a script called "myscript.sh" and you want to pass two parameters to it, you can run it like this:
: ...................
谢谢,但感觉都不是我想要的,这样还是需要处理很多参数,或者传到脚本里面的参数还需要一个地方放着,然后优惠涉及到怎么管理的问题
把变量放在a.sh里
a.sh
port=123
你执行b.sh的第一行 source a.sh
后面可以直接开始用变量名了
【 在 hanleirx 的大作中提到: 】
: 最不会写shell,但是现在遇到一个问题,特来我邮求助。
: 问题是这样的,我的shell里面需要一堆变量,例如
: port
: ...................