tags:

views:

121

answers:

4

Using bash, I have a list of strings that I want to use to replace an int. Here's an example:

day1=Monday
day2=Tuesday
day3=Wednesday
day4=Thursday
day5=Friday
day6=Saturday
day7=Sunday

If I have an int, $dow, to represent the day of the week, how do I print the actual string? I tried this:

echo ${day`echo $dow`}

but get error of "bad substitution". How do I make this work? Note: I can change the $day variables to a list or something.

+1  A: 

Yes, it would be easiest to do this as an array:

day=([1]=Monday [2]=Tuesday ...)
echo "${day[dow]}"
Ignacio Vazquez-Abrams
perfect! I didn't know about the [1]=... [2]=... That's very cool!
User1
You can set the first index and the rest will follow: `day=([1]=Monday Tuesday Wednesday...)`
Dennis Williamson
+1  A: 
case $dow in
  [1234567]) eval echo '$day'$dow ;;
esac

I didn't want to get yelled at for an unsafe use of "eval" :-)

There's probably a more "modern" way of doing this.

Pointy
A: 

You could use variable indirection:

day_var=day$dow
echo ${!day_var}

But you should consider the use of arrays:

days=("Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday" "Sunday")
echo ${days[$[$dow-1]]}
Jürgen Hötzel
I like it, but I can only select one answer.
User1
The use of square brackets the way you have them for the inner set is deprecated (and unnecessary in this case). The current usage is `$(( ... ))` but the array subscript will do the math for you: `${days[dow-1]}`
Dennis Williamson
A: 

In June 1970 (you remember?) the month started with Monday:

for d in {1..7}
do 
     date -d 1970-06-0$d +%A
done 
user unknown
t=7;date -d 'first sunday + '$t'day' +%A maybe more easy to remember.
user unknown