syntax error in shell script

I am creating a shell script. In which, I need to get server name and server IP. I used this command in script.

servername=`cat /etc/hosts|grep `eval hostname`|awk '{print $2}'`

however, when execute script or put set -x to debug, it return:
line 13: syntax error at line 13: `|' unexpected

I typed this line of command at command prompt, it works with exact server name returned. Please help me to identify where is the error. Thanks.

Hi,

Try;

servername=`uname -n`

Regards

Dave

You have doubly nested backtics - some shells have a problem with that try:

servername=$( cat /etc/hosts|grep `eval hostname`|awk '{print $2}' )

Also consider using nslookup, since not all server names will be in /etc/hosts

gull04, jim:

Thanks so much for your prompt advise. I tested two commands. They are all work very well. I will use them. I chnaged my shell from
#!/bin/ksh to #!/bin/bash

My question remaining is, after I check and chnage my shell in script. It is Oracle Linux 5. So shell is bash shell. I used original script to test. it return this error code:

./script.sh: command substitution: line 13: syntax error near unexpected token `|'

It is pointed to the same error as begining. Why shell flavor has big difference?

The big flavor difference is: you are depending on what is called undefined behavior.
POSIX standards no not say what happens with nested backtics, for example. So some nice guy who wrote shellA allows it to work correctly (correctly == your expectations, not really required to work). The evil guy who wrote shellB did not do that. He literally follows the standard

from opengroup.org (POSIX people):