How to print last character of hostname and assign to a variable ?

Hi

How to pass echo output to a variable ?

Does below awk command will get the last character of hostname and assign to a variable - " svr " ?

svr=$( echo `hostname` | awk '{print substr($0,length,1)}' )

Thanks.

Yes it works.
Without the echo command it simplifies to

 svr=$( hostname | awk '{ print substr($0,length,1) }' )

or apply two variable modifiers

h=$(hostname); t=${x%?}; svr=${h#$t}

% chops from the end. ? is one character.
# chops from the beginning. $t is from the previous assignment.

Hello Lim,

Welcome to forums, the BEST way to know any command's output is run it, you could have run it in your box.
You were close, try following to get last character of hostname .

hostname | awk '{print substr($0,length($0))}'

To save it in a variable use(note that backticks are depreciated so use $ instead to store values into variables too):

var=$(hostname | awk '{print substr($0,length($0))}')

Thanks,
R. Singh

Most if not all awk versions have length() default to $0.
So you can say length() and even length .
Likewise, in substr() the 3rd parameter defaults to "unlimited", so can be omitted here, because there is only 1 character left.

1 Like

No need to use temp variable:

$ HN=$(hostname)
$ echo ${HN#${HN%?}}
1 Like

Thanks all

1 Like

Hello Lim,

Appreciate that your are trying to encourage people by thanking them in a post, very good. For THANKING people we do have a mechanism called "THANKS" button at side of each posts's left corner, so you could HIT it for any post which you LIKE/which was helpful.

Thanks for posting in UNIX & LINUX forums, keep learning and keep sharing on this great site, cheers.

Thanks,
R. Singh

echo ${HOSTNAME: -1}
2 Likes