jms1980
jms1980

Reputation: 1075

Setting last digit of a number to a variable in a shell script

I have a number 2014061200 and I am trying to extract the one's digit of this number (0) and set it to a variable $STR, so that $STR would equal 0, because that is in the one's place of the above number.

I made a shell script showing the following:

$NUM=2014061200
$STR= $NUM | tail -c 2
echo $STR

However when I do this I get a blank for $STR instead of the expected result of 0. I mean when I type

echo $NUM | tail -c 2, I do get the output of 0, but how do I get this into a variable?

Thanks

Upvotes: 1

Views: 3268

Answers (2)

Cole Tierney
Cole Tierney

Reputation: 10314

Here's another variation using parameter expansion where ${#num}-1 is the length of the string less 1 and ${num:position:length} is a substring expression:

${num:(${#num}-1):1}

Upvotes: 1

choroba
choroba

Reputation: 241808

Use parameter expansion:

num=2014061200
last=${num: -1}

-1 tells bash to extract one character from the right.

Upvotes: 5

Related Questions