Problem with assigning output of grep + awk to a variable

Hi All,

I am getting the output for the following command when i run it on the unix console.

---------------------------
grep `whoami` /etc/passwd | awk '{print ($1);}' | cut -d ":" -f3
----------------------------

But i made it into a script and tried to print the variable, its showing a syntax error.

tsts.sh
-------------------------------
#!/bin/sh
whoami_code=`(grep `whoami` /etc/passwd | awk '{print ($1);}' | cut -d ":" -f3)`
echo whoami_code=$whoami_code
-----------------------------------

the error is
tsts.sh: syntax error at line 1: `end of file' unexpected

Please help me out.

Thanks in advance..

  • Removed the backticks around the out brackets
  • Added a dollar symobl in front of the first opening bracket
  • removed the brackets around field 1 in the awk print and also the semicolon
whoami_code=$(grep `whoami` /etc/passwd | awk '{print $1}' | cut -d ":" -f3)

Should work.

i tried running that but got the following error.

tsts.sh: syntax error at line 3: `whoami_code=$' unexpected

root@isau02:/data/tmp/testfeld> whoami_code=$(grep `whoami` /etc/passwd | awk '{print $1}' | cut -d ":" -f3)
root@isau02:/data/tmp/testfeld> echo $whoami_code
0 113 114 115

Hi ,

Thankyou...

The error was coming because of #!/bin/sh in the beginning of the script.

-----------------------
#!/bin/sh
whoami_code=$(grep `whoami` /etc/passwd | awk '{print $1}' | cut -d ":" -f3)
echo $whoami_code
--------------------------
When i removed that part it worked... is there any particular reason for that??

Idk, /bin/sh is bash. I tried both, /bin/sh and /bin/bash, both works; no idea.

Btw, use code tags when posting code, logs etc. Then you don't need the -------------.