Reputation: 384
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
Reputation: 785651
You can use:
getIP() {
awk -v h="${1:-domain}" '$0 ~ h{print $1}' /etc/hosts
}
awk
use -v varname=value
ip
if you're just doing an echo
Upvotes: 2