Reputation: 383
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.
Upvotes: 5
Views: 5856
Reputation: 74705
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.
Upvotes: 6