[英]how to pass multiple arguments and read in shell script
I need to read multiple arugments are assign each to different variable in shell script我需要阅读多个参数,将每个参数分配给 shell 脚本中的不同变量
example:例子:
.run.sh --argument1=value1 --argument2=value2 --argument3=value3
In my code I need to read this and assign as,在我的代码中,我需要阅读这个并指定为,
variable1=value1变量 1=值 1
variable2=value2变量 2=值 2
variable3=value3变量 3=值 3
I was trying to read in a loop but not sure how to read the value immediately after the "=" sign我试图循环读取但不确定如何在“=”符号后立即读取值
for i in "$@"
do
case $i in
--argument1)
variable1="..."
shift
;;
esac
done
Set variable1=$2
then shift 2
.设置variable1=$2
然后shift 2
。
Although I would recommend instead using getopts
for parameter parsing.尽管我建议改为使用getopts
进行参数解析。 A good reference would be this blog post by Kevin Sookocheff . Kevin Sookocheff 的这篇博客文章是一个很好的参考。
Perhaps you need an associative array.也许你需要一个关联数组。
#!/usr/bin/env bash
n=1
declare -A array
for f; do
array["variable$((n++))"]=${f##*=}
done
echo "${array[variable1]}"
echo "${array[variable2]}"
echo "${array[variable3]}
Running that against your sample arguments.针对您的样本 arguments 运行它。
./run.sh --argument1=value1 --argument2=value2 --argument3=value3
Output Output
value1
value2
value3
Although an option parser might be better for this kind of situation.尽管选项解析器可能更适合这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.