0

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!

3 Answers 3

2

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

sudo ./v2u $(printf "cap_%06d.png" "$duration")
Sign up to request clarification or add additional context in comments.

1 Comment

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. :-)
2

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"

Comments

0

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"

Comments

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.