Greg
Greg

Reputation: 384

bash: awk print inside function

If I have a function like:

function getIP() {
    local ip=$(cat /etc/hosts | awk '/${1:-domain}/{print $1}')
    echo "$ip"
}

How do I prevent the $1 from ‘print $1’ from becoming the parameter passed to the function?

So basically I’d like to call it and get something like: cat /etc/hosts | awk '/domain/{print $1}'

but I’m currently, with the default parameter, getting: cat /etc/hosts | awk '/domain/{print }'

and with a passed parameter: cat /etc/hosts | awk '/test/{print test}'

I've tried escaping it but that gives me a bash error:

awk: /${1:-domain}/{print \$1}
awk:                      ^ backslash not last character on line

Upvotes: 2

Views: 2731

Answers (1)

anubhava
anubhava

Reputation: 785651

You can use:

getIP() {
    awk -v h="${1:-domain}" '$0 ~ h{print $1}' /etc/hosts
}
  • to pass a variable to awk use -v varname=value
  • no need to use useless cat
  • no need to create a local variable ip if you're just doing an echo

Upvotes: 2

Related Questions