Results 1 to 7 of 7
Trying to get this for loop in bash script to work tried lots of combinations for $n
As in ‘”’$n’ “’”$n’ and lots more any help would be greatly appreciated.
...
- 04-09-2009 #1Just Joined!
- Join Date
- Mar 2009
- Posts
- 11
help with for loop
Trying to get this for loop in bash script to work tried lots of combinations for $n
As in ‘”’$n’ “’”$n’ and lots more any help would be greatly appreciated.
for (( n=1; n<=20; n++ ))
do
month_$n=`(date --date='$n days ago' '+%m')`
month_$n=`echo $month_$n|sed 's/^0*//'`
day_$n=`(date --date='$n days ago' '+%d')`
day_$n=`echo $day_$n|sed 's/^0*//'`
year_$n=`(date --date='$n days ago' '+%Y')`
echo $month_$n/$day_$n/$year_$n
done
- 04-09-2009 #2Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
If you're trying to construct the variable name with $n then you have to use the eval command. Also, if you use the $n within the command you can't place it within single quotes because it won't be evaluated. Here's you 1st line corrected:
Code:eval month_$n=$(date --date="$n days ago" '+%m')
- 04-09-2009 #3Just Joined!
- Join Date
- Mar 2009
- Posts
- 11
Thanks for your help but its still not working right now i get
for (( n=1; n<=20; n++ ))
do
eval month_$n=$(date --date="$n days ago" '+%m')
eval day_$n=$(date --date="$n days ago" '+%d')
eval year_$n=$(date --date="$n days ago" '+%Y')
echo $month_$n/$day_$n/$year_$n
done
gives me
1/1/1
2/2/2
3/3/3
4/4/4
5/5/5
6/6/6
7/7/7
8/8/8
9/9/9
- 04-09-2009 #4Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
Again if you're going to construct a variable name using $n then you have to use the eval command.
Code:eval echo \$month_$n/\$day_$n/\$year_$n
- 04-10-2009 #5Just Joined!
- Join Date
- Mar 2009
- Posts
- 11
Sorry I tried the eval but I didn’t use the \ I will give it a try
One more question why do I need the \
Not trying to be a pain but I’d rather understand the meaning of what I’m doing than just doing it if you know what I mean.
And thank you for your help its much appreciated.
- 04-10-2009 #6Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
In bash the backslash (\) is the escape character. It preserves the literal value of the next character which in this case is the dollar sign ($). If it wasn't there the eval command would treat treat parts of the command like $month_ as a variable and expand it. Since that isn't defined it would be replaced with nothing. So, assuming in this example n=1, not using \'s the command eval constructs would look like:
With the backslash the command constructed by eval is:Code:echo 1/1/1
Code:echo $month_1/$day_1/$year_1
- 04-11-2009 #7Just Joined!
- Join Date
- Mar 2009
- Posts
- 11
I understand and thanks for taking time to explain it to me.


Reply With Quote