2

I'm trying to figure out how I can make a script I'm running to be more readable. I have multiple commands which I would like to separate from the actual output.

My first thought was to use set -x, but this was still lost between the output of the actual commands. So I've found and applied two bash functions which I call before each function:

#!/usr/bin/env bash

function c_echo(){
    local color=$1;
    shift
    local exp=$@;
    if ! [[ $color =~ '^[0-9]$' ]] ; then
       case $(echo $color | tr '[:upper:]' '[:lower:]') in
        black) color=0 ;;
        red) color=1 ;;
        green) color=2 ;;
        yellow) color=3 ;;
        blue) color=4 ;;
        magenta) color=5 ;;
        cyan) color=6 ;;
        white|*) color=7 ;; # white or invalid color
       esac
    fi
    tput setaf $color;
    echo $exp;
    tput sgr0;
}

function script_cmd() {
    c_echo YELLOW "\$ $@";
    "$@";
}

export -f script_cmd
export -f c_echo

Later inside my script:

c_echo GREEN "1. Download insulin (2HIU) and Leucine zipper (2ZTA)."

script_cmd wget https://files.rcsb.org/view/2HIU.cif

This works perfectly, but fails on commands which actually do redirection. Is there a way I can work around this?

script_cmd charmm < setup_2zta.inp > setup_2zta.out
pynexj
  • 19,215
  • 5
  • 38
  • 56
Bartlomiej Lewandowski
  • 10,771
  • 14
  • 44
  • 75

1 Answers1

1

You can redirect the colorful output to stderr:

function script_cmd() {
    c_echo YELLOW "\$ $@" >&2
    #                     ^^^
    "$@";
}

If you want to colorize the whole charmm < setup_2zta.inp > setup_2zta.out command you can

script_cmd bash -c 'charmm < setup_2zta.inp > setup_2zta.out'

or

function script_cmd() {
    c_echo YELLOW "\$ $@" >&2
    #                     ^^^
    eval "$@";
    #^^^
}

script_cmd 'charmm < setup_2zta.inp > setup_2zta.out'
pynexj
  • 19,215
  • 5
  • 38
  • 56