我正在研究一个shell脚本,以便从数据库中获取数据并根据用户提供的输入返回结果。
但是,我想限制用户传递特定数目的最大值(例如10),以逗号分隔。即使用户传递了10个以上的值,我的shell脚本也应限制该用户,并仅从用户提供的列表中执行10个。
我能够获取所有用户提供的值的结果,但无法确定如何将其限制为特定数字。
IDs=a1,b2,c3,d4,e5,f6,g7,h8,i9,j10,k11,l12,m13,n14
# Above are User provided sample alphanumeric values
for i in $(echo $IDs | sed "s/,/ /g")
do
echo "Fetching results for $i by running sql against DB"
done
除了shell脚本外,我只通过忽略其余部分来获取前10个逗号分隔的值(例如,在脚本中,需要选择直到“ a1”到“ j10”之间的值,然后忽略其余部分)并针对DB执行相同的操作。
任何帮助将不胜感激。预先感谢!
答案 0 :(得分:1)
如果您将ID读入数组,则可以使用参数扩展来仅获取该数组的前10个元素,如下所示:
#!/usr/bin/env bash
# ^^^^- NOT /bin/sh; arrays require a shell with ksh extensions.
IDs=a1,b2,c3,d4,e5,f6,g7,h8,i9,j10,k11,l12,m13,n14 # original input
IFS=, read -r -a id_arr <<<"$IDs" # transform into an array
max_count=10 # input w/ count to process
for i in "${id_arr[@]:0:max_count}"; do # iterate only over that many
echo "Fetching results for $i by running sql against DB"
done
在"${arrayname[@]:0:max_count}"
中,0
是起始位置(我们从头开始),而max_count
是要迭代的项目数。参见the bash-hackers' wiki page on parameter expansion。
答案 1 :(得分:0)
有很多方法可以将这一片切成小块。
这是一个需要在OPs当前代码中添加少量(cut
)来限制已处理项目数的选项:
$ IDs=a1,b2,c3,d4,e5,f6,g7,h8,i9,j10,k11,l12,m13,n14
$ echo ${IDs} | cut -d"," -f1-10
a1,b2,c3,d4,e5,f6,g7,h8,i9,j10
$ for i in $(echo ${IDs} | cut -d"," -f1-10 | sed 's/,/ /g')
do
echo "Fetching results for $i by running sql against DB"
done
Fetching results for a1 by running sql against DB
Fetching results for b2 by running sql against DB
Fetching results for c3 by running sql against DB
Fetching results for d4 by running sql against DB
Fetching results for e5 by running sql against DB
Fetching results for f6 by running sql against DB
Fetching results for g7 by running sql against DB
Fetching results for h8 by running sql against DB
Fetching results for i9 by running sql against DB
Fetching results for j10 by running sql against DB