我制作了一個腳本來創建 Google Cloud Scheduler 任務。我想在 bash 中創建一個回圈以不重復所有命令,所以我做了這個:
#!/bin/bash
declare -A tasks
tasks["task1"]="0 5 * * *"
tasks["task2"]="0 10 * * *"
for key in ${!tasks[@]}; do
gcloud scheduler jobs delete ${key} --project $PROJECT_ID --quiet
gcloud scheduler jobs create http ${key} --uri="https://example.com" --schedule="${tasks[${key}]}" --project $PROJECT_ID --http-method="get"
done
在這個回圈中,我只是使用我的陣列鍵為 cron 命名,并且我正在使用${tasks[${key}]}cron 模式的值。
但是現在我遇到了一個問題,因為我想--uri按任務設定不同的。例如,我想要https://example1.comtask1 和https://example2.comtask2 等......
所以我想在任務陣列中添加另一個鍵,例如:
tasks["task1"]["uri"]="https://example1.com"
tasks["task1"]["schedule"]="0 5 * * *"
tasks["task2"]["uri"]="https://example2.com"
tasks["task2"]["schedule"]="0 10 * * *"
并在我的回圈中使用它。我怎樣才能做到這一點 ?或者也許 bash 有更好的方法來管理我的問題?
uj5u.com熱心網友回復:
bash不支持多維陣列;您可能要考慮的是 2 個對相應條目使用相同索引的陣列,例如:
declare -A uri schedule
uri["task1"]="https://example1.com"
schedule["task1"]="0 5 * * *"
uri["task2"]="https://example2.com"
schedule["task2"]="0 10 * * *"
由于兩個陣列都使用相同的索引集,您可以使用單個for回圈來處理兩個陣列,例如:
for key in "${!schedule[@]}" # or: for key in "${!uri[@]}"
do
echo "${key} : ${schedule[${key}]} : ${uri[${key}]}"
done
這會產生:
task1 : 0 5 * * * : https://example1.com
task2 : 0 10 * * * : https://example2.com
uj5u.com熱心網友回復:
您可以像這樣模擬多維陣列:
#!/usr/bin/env bash
declare -A task1=([uri]="https://example1.com" [schedule]="0 5 * * *")
declare -A task2=([uri]="https://example2.com" [schedule]="0 10 * * *")
declare -a tasks=(task1 task2)
declare -n task
for task in "${tasks[@]}"; do
echo "task uri=${task[uri]}"
echo "task schedule=${task[schedule]}"
done
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/455236.html
標籤:重击
下一篇:Bash'ls'不接受*通配符
