2

I have found many answers about this on StackOverflow but I can't apply them to my code.

I used this command to get last day of current month:

LASTDAY=`cal $(date +"%m %Y") | grep . | fmt -1 | tail -1`

then I use this code:

for i in {1..${LASTDAY}}
do
    # code for processing here!
done

But always get this warning: line 12: [: {1..31}: integer expression expected

and i is {1..31} but I expected i is a number in range [1,31]

I have tried this:

LASTDAY=$((LASTDAY+0))

LASTDAY=$( echo "$LASTDAY - 0" | bc )

LASTDAY=$(printf "%d" "$LASTDAY")

but it can't solve this problem. What's wrong in my code? and how to fix it?

Thanks in advanced.

3
  • I'm not a bash head, but I think the range expression like {1..31} maybe a new feature to bash. What version are you using? bash --version, should output your version. Add that bit of information to your question above. Good luck. Commented Oct 1, 2013 at 3:30
  • You are right. However, I have run this expression many times but it is failed in the case I asked above. FYI, my bash version is: 3.2.25(1)-release (x86_64-redhat-linux-gnu) Commented Oct 1, 2013 at 3:44
  • Brace expansion has been in bash for a long time. However, it occurs prior to parameter expansion; since the braces do not contain two integer literals, the expression is treated literally as the string {1..${LASTDAY}}. Then parameter expansion is applied to produce {1..31}. That string is rejected by the code that receives $i, since that string is not an integer. Commented Oct 1, 2013 at 13:01

1 Answer 1

9

Use the following instead of for i in {1..$Lastday}

for i in $(seq 1 ${LASTDAY}) ; do  echo $i done

This will work.

Sign up to request clarification or add additional context in comments.

1 Comment

Be careful about range length - some shells have limit on 64 KiB line length. In bash use may use usual for (( expr1 ; expr2 ; expr3 )) ; do list ; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.