5

So I introduce a number to my script, just like this:

./script 795

and I'd like to extract each digit from that number and check if it's smaller than 7. Something like:

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

I'd like to know how to extract each digit.

psmears
  • 26,070
  • 4
  • 40
  • 48
magalenyo
  • 275
  • 6
  • 17
  • Possible duplicate of [How to perform a for loop on each character in a string in BASH?](http://stackoverflow.com/questions/10551981/how-to-perform-a-for-loop-on-each-character-in-a-string-in-bash) – Mad Physicist Mar 02 '16 at 12:19
  • Your question has been answered here: http://stackoverflow.com/q/10551981/2988730. The input variable is argument 1: `$1` inside the script. – Mad Physicist Mar 02 '16 at 12:20

1 Answers1

6

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

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

To do this for each character, then 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

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

Tom Fenech
  • 72,334
  • 12
  • 107
  • 141