4

Simple for loop on the command line:

cobrakai$for((i=1;i<=10;i+=1)); do echo "Welcome $i times"; doneWelcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
Welcome 6 times
Welcome 7 times
Welcome 8 times
Welcome 9 times
Welcome 10 times

...and if I want to put a date command in I can do this:

cobrakai$for((i=1;i<=10;i+=1)); do  echo $(date -v -1d "+%Y-%m-%d"); done
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04
2013-08-04

But, of course, I actually want the dates to count down, so I subsitute in the $i for the 1 but find I get...

for((i=1;i<=10;i+=1)); do  echo $(date -v -$id "+%Y-%m-%d"); done
-: Cannot apply date adjustment
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

I presume that's because $id is recognised as $(id) not ($i)d, so I try,

cobrakai$for((i=1;i<=10;i+=1)); do  echo $(date -v -($i)d "+%Y-%m-%d"); done
-bash: command substitution: line 1: syntax error near unexpected token `('
-bash: command substitution: line 1: `date -v -($i)d "+%Y-%m-%d"'

and

for((i=1;i<=10;i+=1)); do  echo $(date -v -$i d "+%Y-%m-%d"); done
date: illegal time format
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
            [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]

but I'm getting nowhere - what's the key?

5

You can use

-"$i"d

or

-${i}d

I am not able to test the solution, though, as my date command does not recognize the -v -1d option.

0

If you are using a newer bash/gnu utility set:

$ for((i=1;i<10;i+=1)) do date "+%Y-%m-%d" --date="${i} day"; done

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.