我正在制作一个 bash 脚本,需要使用特定 ID 运行命令。但一个ID只能使用10次。之后ID应该改变
例如我有三个ID
ID=(abcd1
abcd2
abcd3)
echo $ID
现在,当该脚本执行 10 次时,ID 的值应更改为 abcd2.. 10 次后,ID 的值应更改为 abcd3
我在谷歌上搜索但找不到这样的东西
编辑:我只是想到在这种情况下使用 json 的想法,所以我又创建了一篇文章这里
答案1
您可以在脚本中放置计数器。然后让脚本在每次运行时更新它们。
#!/usr/bin/env bash
_list=(
abc
def
ghi
)
_list_index=0 # autoupdate
_list_usage_counter=0 # autoupdate
max_uses=10
if [ $((_list_usage_counter)) -eq $((max_uses - 1)) ] ; then
# reset counter
sed -Ei \
-e "s/^(_list_usage_counter)\=${_list_usage_counter}( # autoupdate)\$/\1=0\2/" \
"$(readlink -f "$0")"
_list_usage_counter=0
# update list index
sed -Ei \
-e "s/^(_list_index)\=${_list_index}( # autoupdate)\$/\1=$((++_list_index))\2/" \
"$(readlink -f "$0")"
fi
# make sure index is not out of bounds
if [ $_list_index -ge ${#_list[@]} ] ; then
echo "no more items to use"
exit
fi
# ... do stuff ...
echo "item: ${_list[_list_index]}"
echo "used: $((_list_usage_counter + 1))"
# update counter
sed -Ei \
-e "s/^(_list_usage_counter)\=${_list_usage_counter}( # autoupdate)\$/\1=$((++_list_usage_counter))\2/" \
"$(readlink -f "$0")"
答案2
您可以将“计数器”存储到临时文件中:
#!/bin/bash
ID=(abcd1 abcd2 abcd3)
#if script run for the first time create "file" counters
id_file="/tmp/$(basename ${0})_id"
us_file="/tmp/$(basename ${0})_usage"
if [[ ! -f $id_file ]]; then
echo "0" > $id_file
fi
if [[ ! -f $us_file ]]; then
echo "0" > $us_file
fi
#set variables
max_usage=10
id="$(cat $id_file)"
usage="$(cat $us_file)"
#if all ids used, exit script
if [[ $id -eq ${#ID[@]} ]]; then
echo "No more ids available! Create new ones and delete '$id_file' and '$us_file' files."
exit
fi
if [[ $usage -lt $max_usage ]]; then
usage="$(( $(cat $us_file) + 1 ))"
echo $usage > $us_file
# do your stuff
echo "Your id is: ${ID[$id]}."
else
#reset usage and change (use next) id
usage="1"
echo "1" > $us_file
id=$((id+1))
echo "$id" > $id_file
if [[ $id -lt ${#ID[@]} ]]; then
echo "Your id x is: ${ID[$id]}."
else
echo "No more ids available! Create new ones and delete '$id_file' and '$us_file' files."
fi
fi