Signup/Sign In
APRIL 17, 2023

printf: "09" and "08" are invalid octal values

    If you're writing a bash script, and you want to print numbers with leading zeros, you might run into an error when using the printf function with the numbers 08 or 09. In this article, we'll explain what causes this error and how to fix it.

    First, let's take a look at a simple bash script that uses printf to print numbers with leading zeros:

    printf "%04d" "09"
    printf "%04d" "08"
    printf "%04d" "07"
    printf "%04d" "06"

    This script is designed to print each number with zeros to a total length of four digits. However, when you run this script, you'll see an error message for the numbers 08 and 09:


    ./rename.sh: line 3: printf: 09: invalid number
    0000
    ./rename.sh: line 4: printf: 08: invalid number
    0000
    0007
    0006

    So, what's causing this error? The problem is that in bash, numbers that start with a zero are interpreted as octal numbers. The digits 0-7 are valid in octal notation, but 8 and 9 are not.

    To fix this error, we need to tell bash to interpret the numbers as decimal numbers instead of octal numbers. There are a few ways to do this, but one simple way is to use the ${variable#pattern} parameter expansion to strip the leading zero from the number.

    a="09"
    printf "%04d\n" "${a#0}"

    This will output:


    0009

    You can also use bash's arithmetic evaluation syntax (( ... )) to convert numbers to decimal before passing them to printf.

    printf "%04d\n" $(( 10#09 ))
    printf "%04d\n" $(( 10#08 ))
    printf "%04d\n" $(( 10#07 ))
    printf "%04d\n" $(( 10#06 ))

    This will output:


    0009
    0008
    0007
    0006

    You can also remove the leading zero from a variable (i.e., day) as follows:

    if [ ${day:0:1} == 0 ]; then
      day=${day:1:1}
    fi

    Now you know how to fix the error that can occur when using printf with the numbers 08 or 09 in bash scripts. Happy coding!

    Pradeep has expertise in Linux, Go, Nginx, Apache, CyberSecurity, AppSec and various other technical areas. He has contributed to numerous publications and websites, providing his readers with insightful and informative content.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS