0

I am still new to bash, so I was hoping someone more experience than me would be able to help me. I have the following bit of code:

DAY1=$(date +"%d/%b/%Y")
DAY2=$(date --date="-1 days" +"%d/%b/%Y")
...
DAY14=$(date --date="-13 days" +"%d/%b/%Y")
COUNT=0

What I would like to accomplish is to refer to the substituted commands as something like

$DAY($COUNT+1)

to produce variables from $DAY1 to $DAY14. That bit of code obviously doesn't work, but I needed some ideas on how to make this happen. I use a loop that increments the COUNT variable like so:

for i in $(seq 1 14); do
  let COUNT+=1
done
1
  • 1
    How about using an array? Commented Dec 9, 2013 at 1:24

2 Answers 2

1

Don't use eval; it's a bad habit to get into. If you don't want to use an array, use indirect parameter expansion.

DAY1=$(date +"%d/%b/%Y")
DAY2=$(date --date="-1 days" +"%d/%b/%Y")
...
DAY14=$(date --date="-13 days" +"%d/%b/%Y")

COUNT=7
var="DAY$COUNT"
echo "${!var}"   # Displays the value of $COUNT7
Sign up to request clarification or add additional context in comments.

Comments

1

You could construct the variable expression and use eval to execute the command. For example:

for i in {1..14}; do
  let COUNT+=1

  command=echo DAY${COUNT}
  eval $command

done

Another approach, that might make more sense would be to use bash arrays.

1 Comment

I need to pass the variables into grep, so an array would probably make more sense here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.