PhatHV
PhatHV

Reputation: 8141

How to convert string to integer in Bash?

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.

Upvotes: 2

Views: 12889

Answers (1)

CS Pei
CS Pei

Reputation: 11047

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

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

This will work.

Upvotes: 9

Related Questions