04 April 2012

Prettifying command output in scripts.

This is so simple but so nice, that I had to share. Often, I want to create a small script which gives me some information, using another program, and I want to display it in some way which looks nice.

For example:

% tmux ls
dev: 1 windows (created Wed Apr  4 14:54:56 2012) [116x34] (attached)
main: 5 windows (created Wed Apr  4 14:31:07 2012) [116x34] (attached)

Can be wrapped up in a prettifying script, like so:

echo "Running tmux sessions:"
tmux ls

Which gives us:

Running tmux sessions:
dev: 1 windows (created Wed Apr  4 14:54:56 2012) [116x34] (attached)
main: 5 windows (created Wed Apr  4 14:31:07 2012) [116x34] (attached)

But this doesn't look too nice, and if there's a lot of output from different things, might just become one big block of text.

Never fear! With sed and pipes to the rescue, we can prettify things further. Indentation is one example of this, by replacing the start of each line output by 'tmux ls' with some whitespace. Our script might become:

echo "Running tmux sessions:"
tmux ls | sed "s/^/    /"

Which would give us:

Running tmux sessions:
    dev: 1 windows (created Wed Apr  4 14:54:56 2012) [116x34] (attached)
    main: 5 windows (created Wed Apr  4 14:31:07 2012) [116x34] (attached)

Or even nicer:

echo "Running tmux sessions:"
tmux ls | sed "s/^/--> /"

Which would give us:

Running tmux sessions:
--> dev: 1 windows (created Wed Apr  4 14:54:56 2012) [116x34] (attached)
--> main: 5 windows (created Wed Apr  4 14:31:07 2012) [116x34] (attached)

Nice, and very very simple.

Categories: All articles terminal