Schwaitz
Schwaitz

Reputation: 471

How to define a series of bash commands as a string?

Right now some of the code in my .zshrc file looks like this:

inetFunction(){
    echo ${LRED}IP Address:${NC}
    ifconfig en0 | grep "inet " | awk '{print $2}'
}

$LRED is defined as changing the color to Light Red, and $NC is setting it back to normal. I implement the inetFunction with the code alias inet='inetFunction'. The output of the command is

IP Address:
xx.x.xx.xxx

where the "IP Address:" is in red. I wanted to make the IP Address green, but for some reason, when I try any of these, it doesn't work:

${GREEN}ifconfig en0 | grep "inet " | awk '{print $2}'

ifconfig en0 | grep "inet " | ${GREEN}awk '{print $2}'

${GREEN}ifconfig en0 | grep "inet " | awk '{${GREEN} print $2}'

I even tried setting the whole thing to a variable like:

variable='ifconfig en0 | grep "inet " | awk '{print $2}''

and then trying to do echo ${GREEN} $variable, but it still doesn't work.

Any ideas?

Upvotes: 2

Views: 155

Answers (2)

Adaephon
Adaephon

Reputation: 18339

As already noted in John Kugelman's answer ${GREEN} needs to be printed in order to take affect.

As you are running awk anyway, you can just let it do the work:

ifconfig en0 | awk '/inet / {print "'${GREEN}'" $2 "'${NC}'"}'
ifconfig eno1 | awk "/inet / {print \"${GREEN}\" \$2 \"${NC}\"}"   

This allows for more control what to color, especially with more complex awk programs.

Obviously the quoting necessary for that is anything but beautiful. $2 needs to be quoted from the shell, so that it can be recognized by awk. ${GREEN} and ${NC} must not be quoted from the shell, so that they can be replaced by the shell. But as they are now just strings to awk, they need to be inside double quotes for awk; these double quotes need also need to be quoted from the shell.

To simplyfy this you can pass set variables for awk on the command line with the -v variable=value parameter:

ifconfig en0 | awk -v green="$GREEN" -v nc="$NC" '/inet / {print green $2 nc}' 

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361605

$GREEN needs to be echoed. It's a set of ANSI color codes that your terminal recognizes as a signal to change the text color.

echo -n "$GREEN"
ifconfig en0 | grep "inet " | awk '{print $2}'
echo -n "$NC"

Or, condensed:

echo "$GREEN$(ifconfig en0 | grep "inet " | awk '{print $2}')$NC"

Also, as @Jens points out you can combine the grep and awk commands like so:

echo "$GREEN$(ifconfig en0 | awk '/inet / {print $2}')$NC"

Upvotes: 2

Related Questions