Reputation: 469
I am writing a bash script that does various stuff but when it starts, it checks if there has been a crash and so tries to load its variables from a logfile.
The log file has the following format:
1stline: var1:var2:var3:var4:var5 # : is a delimeter
2ndline: number # [0-9]
3rdline: var6:var7:var8 # : is a delimeter
So as you can tell I have 9 variables that I wish to load from this file if there has been a crash.
I am trying to write some code in bash to do it but I am getting stuck.
For instance my Idea is to create an array, and add every variable which is read from the logfile there. But I am having troubles writing this code.
if [ -s ${crashfile} ] # file exists => crash has occured
then
declare -a loadvars
while IFS= read -r line
# What do I do in here ?
done < ${crashfile}
else # file doesn't exist => cold start
# bla
# bla
# bla
fi
The problem is focused inside the first while loop. Meaning I am thinking that I have to create another while loop to tokenize the string accordingly? But then again, the second line has only a number with no delimeter so this should be treated carefully aswell?
I can do it with python/C whatever but the point is to do it with bash.
Thanks in advance.
Upvotes: 0
Views: 95
Reputation: 19545
If you are really sure of your 9 variables:
IFS=$':\n' read -r -d '' var1 var2 var3 var4 var5 number var6 var7 var8
printf '<%s>\n' "$var1" "$var2" "$var3" "$var4" "$var5" "$number" "$var6" "$var7" "$var8"
If you need to read an undefined amount of values, then use an array:
IFS=$':\n' read -r -d '' -a vars
printf '<%s>\n' "${vars[@]}"
Upvotes: 1
Reputation: 50750
Using a temporary array:
vars=()
while IFS=: read -ra temp; do
vars+=("${temp[@]}")
done < file
printf '<%s>\n' "${vars[@]}"
For your sample (except #
comments), it outputs:
<var1>
<var2>
<var3>
<var4>
<var5>
<number>
<var6>
<var7>
<var8>
Upvotes: 3