Bash: how to extract numbers from a number

So, I entered the number in my script, like this:

./script 795

and I would like to extract each digit from this number and check if it is less than 7. Something like:

if [ 7 -le 7 ]
then 
echo "The first digit is smaller than 7"

I would like to know how to extract each digit.

+4
source share
1 answer

You can use a substring to extract the first character of the first argument in a script:

if [ ${1:0:1} -lt 7 ]; then
    echo "The first digit is smaller than 7"
fi

To do this for each character, you can use a loop:

for (( i = 0; i < ${#1}; ++i )); do
    if [ ${1:$i:1} -lt 7 ]; then
        echo "Character $i is smaller than 7"
    fi
done

Notice that I changed -le(less than or equal to) to -lt(less) to make your message correct.

+5
source

All Articles