tags:

views:

20

answers:

3

I am trying to compare the $duration variable to an int, to see how long it is. I need to deturmine how many 0's to append to the file name to maintain clean names e.g.

cap_000001.png

cap_002938.png

My current statement is:

if [ $duration < 1000 ]; then
    sudo ./v2u cap_000$duration.png
    echo 1000 seconds
fi
if [ $duration < 100 ]; then
    sudo ./v2u cap_0000$duration.png
    echo 100 seconds
fi
if [ $duration < 10 ]; then
    sudo ./v2u cap_00000$duration.png
    echo 10 seconds
fi

Thanks for Helping!

If someone has an easier solution for naming the files with a consistent number of digits that would be great too!

+2  A: 

Try man printf. It is far, far better for this task than a bunch of if blocks.

sudo ./v2u $(printf "cap_%06d.png" "$duration")
Amber
Agree that it's a much more superior solution. +1. I wrote a direct answer to the OP's question too, as well a fully-spelt-out version of your approach. I hope you won't mind. :-)
Chris Jester-Young
+1  A: 

To directly answer your question about comparing numbers:

if [ "$duration" -lt 1000 ]; then

You get the idea. :-)

Amber's answer is, of course, much better from a forest-instead-of-trees point of view:

printf "cap_%06d.png" "$duration"
Chris Jester-Young
A: 

If you prefer to use comparison operators such as > instead of -lt, Bash does numeric comparisons like this:

if (( duration < 1000 )); then

However, printf is the way to go.

This will give a similar affect to the printf approach, also without having to do any if statements:

num=000000$duration
sudo ./v2u "cap_${num: -6}.png"
Dennis Williamson