2

I'm new to bash and sed. I'd like to take the output of who and indent each line, coloring the username in the process. Here's what I have so far:

#!/bin/bash
BOLD="\e[1m"
UNBOLD="\e[0m"
GREEN="\e[32m"
DEFAULT="\e[39m"

who | sed "s@\\([a-z_][a-z0-9_]{0,30}\\) \\(.*\\)@\\t$BOLD$GREEN\\1$DEFAULT$UNBOLD\\2@"

Right now it just prints the output without any changes. I'm pretty sure the problem has to do with escaping, but I'm not sure what needs it and what doesn't.

Thanks!

1 Answer 1

2

You have two problems. The first one is that your command is not doing what you're expecting. Let's fix that first. I guess you want to write the user in bold green, and the rest in default unbold. This should be better:

#!/bin/bash
bold="\e[1m"
unbold="\e[0m"
green="\e[32m"
default="\e[39m"
who | sed "s/^\([[:alpha:]_]\+\)\(.*\)/$bold$green\1$default$unbold\2/"

Or is it really better? you see the ugly codes instead of the nice colors. And this is your second problem. This is how we'll fix it:

#!/bin/bash
bold=$'\e[1m'
unbold=$'\e[0m'
green=$'\e[32m'
default=$'\e[39m'
who | sed "s/^\([[:alpha:]_]\+\)\(.*\)/$bold$green\1$default$unbold\2/"

or, if you don't like ANSI-C quotings:

#!/bin/bash
bold=$(echo -e "\e[1m")
unbold=$(echo -e "\e[0m")
green=$(echo -e "\e[32m")
default=$(echo -e "\e[39m")
who | sed "s/^\([[:alpha:]_]\+\)\(.*\)/$bold$green\1$default$unbold\2/"

Note. It is considered very bad practice to use uppercase variable names in . I know you'll see a lot of people doing it, but it's really wrong. That's why I lowercased all your variables.

Sign up to request clarification or add additional context in comments.

2 Comments

Regarding the variable names: is there any particular reason it's bad practice? The tutorial I'm following seems to use uppercase for anything intended to be a constant and lowercase for actual variables.
@drwhattheheck Between yesterday and this morning there were 2 questions here on SO about some bash script that didn't work. The reason was that the posters (2 different guys) used a variable called PATH and hence screwed up everything. They would have saved hours if they only had respected this: use lowercase variable names in bash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.