0

I wrote a function inside a bash script with some help:

function test() {
    temp=$(cat /etc/passwd | grep $(whoami) | awk -F : "{print $`echo $1`}")
    echo "$temp"
}

I give it a number X and it should print the Xth column from the users entry in the passwd file.

echo $(test "3")

...will give me the entry of the third column. I have trouble understanding how the awk part works. How does the echo part in

"{print $`echo $1`}" 

access the functions $1 and not the $1 from the pipe?

8324
  • 66
  • 9

1 Answers1

3

You're mixing up awk and shell and misunderstanding what awk is for plus some shell fundamentals and so creating a complicated mess. All you need is:

mytest() {
    awk -F':' -v col="$1" -v me="$(whoami)" '$1==me{print $col}' /etc/passwd
}

mytest 3

I renamed the function "test" to "mytest" since "test" is the name of a shell builtin.

Get the books Effective Awk Programming, 4th Edition, by Arnold Robbins and Shell Scripting Recipes by Chris Johnson.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185
  • 1
    I tried to combine a few new things I'm learning at the moment. Thank you for the suggestion. – 8324 Feb 07 '18 at 13:29
  • 1
    You're welcome. Be careful where you're learning from as online scripts and tutorials are 95% nonsense. Whatever you read that led to the shell and awk scripts you created - delete those bookmarks! – Ed Morton Feb 07 '18 at 13:31