在下面的腳本中,parseTask設置從給定文件中提取的全局變量topic
和points
。然後打印任務名稱(來自文件名)及其主題。變量中的Bash關聯數組密鑰
BASE_DIR=/root/devops/tasks
function nextSection {
if [ "$section" == "topic" ]; then
section="points"
else
section="topic"
fi
}
function parseTask {
section=""
while read line
do
if [ "$line" == "---" ]; then
nextSection
continue
elif [ "$section" == "topic" ]; then
topic=$line
elif [ "$section" == "points" ] && [ "$line" != "" ]; then
IFS=/; read -a fields <<<"$line"
points=$((${fields[1]}-${fields[0]}))
fi
done < "$1/README.txt"
}
for task in $BASE_DIR/*
do
parseTask "$task"
if [ "$points" -eq 0 ]; then
continue
fi
local taskName=${task:${#BASE_DIR}+1}
echo "taskName: $taskName"
echo "topic: $topic"
echo
done
當我運行它時,我得到以下(預期)輸出。
taskName: awesome product function
topic: computer sciencetaskName: calculate product
topic: arithmetictaskName: sum function
topic: computer science
我想定義從TASKNAME主題的映射,所以我把它改成
declare -A taskTopics
for task in $BASE_DIR/*
do
parseTask "$task"
if [ "$points" -eq 0 ]; then
continue
fi
local taskName=${task:${#BASE_DIR}+1}
echo "taskName: $taskName"
echo "topic: $topic"
echo
taskTopics[$taskName]=$topic
done
但現在我得到一個錯誤:
file.sh on line 13: /README.txt: No such file or directory
file.sh on line 41: taskTopics[$taskName]: bad array subscript
我可以用任何幫助弄清楚這裏發生了什麼。
感謝
這可能幫助:http://www.shellcheck.net/和[如何調試bash腳本?](http://unix.stackexchange.com/q/155551/74329) – Cyrus
一問題(我認爲這是你錯誤的原因):當你調用'parseTask'時,你也已經全局改變了'IFS'的值。使用'IFS =/read -a字段<<<「$ line」'(使用* no *分號)。相關:*總是*引用參數擴展,除非你有一個非常好的理由不要。 – chepner
謝謝@chepner,就是這樣。 –