bash script, understanding variables
Below is a snippet from a script I'm working on.
Basically it looks at the timestamp in a log file and puts this value into a variable and then prints it. It's working ok while inside the loop but then, when I'm finished reading the file, the variables are both set to 0. This is driving me crazy! Can someone please explain to me why this is happening. In this case I expect it to print the last timestamp in the file. Like everything else the answer is probably quite obvious when you know it :) Many thanks! Code:
#! /bin/bash |
well, it's an age old bash thing.
the read variables only work in the while loop, annoying isn't it? you will find that if you run it in ksh it will work. if you have it that is. /bin/sh won't work either if on linux as it's bash in drag. |
When piping the output of the tail command to the while loop, the loop itself is executed in a subshell. When the loop exits and the subshell execution is terminated, all the variables assigned in the subshell are lost. To avoid this behaviour you can use "process substitution", as in
Code:
while read line; do |
Thanks alot for your comments!
Process substitution indeed looks like they way to go for me. |
or /bin/ksh
;) |
Quote:
Using ksh for the script was my plan from the beginning but a few date issues made me go with bash instead. That might change before it's finished though... |
All times are GMT -5. The time now is 08:41 PM. |