0

I am display the 256 colors for tput by colouring tho background colour using the following bash function.

 tput-bgcolours ()
 {
    for color in {0..255}; do
        bg=$(tput setab $color)
        echo -n $bg" "
    done
    echo $(tput sgr0)
 }

How can I pass a range of values to the function rather that looking all colours from 0 to 255?

Andy Dalton
  • 13,993
Pietru
  • 389
  • 1
  • 17

2 Answers2

1

You can do:

tput-bgcolours()
{
    for color in "$@"; do
        tput setab $color
        printf " "
    done
    tput sgr0
}

tput-bgcolours {0..10} {30..40}

The "$@" is the set of arguments to the function. Now, the caller of the function can pass the values that they're interested in printing.

This also has the benefit that you don't have to use a range:

tput-bgcolours 1 7 15 8 1
Andy Dalton
  • 13,993
1

A couple of alternatives:

  • printf is in general preferred over echo.
  • One do not need to echo tput

sh compatible

tput-bgcolours() {
    for color in $(seq "$1" "$2"); do
        tput setab "$color"
        printf ' '
    done
    tput sgr0
}

bash loop

tput-bgcolours() {
    for (( c = $1; c <= $2; ++c )); do
        tput setab "$c"
        printf ' '
    done
    tput sgr0
}

Usage:

tput-bgcolours FROM TO

I.e.

tput-bgcolours 0 16

You could of course also add a test in the functions like (test if length of arg is empty):

if [ -z "$1" ] || [ -z "$2" ]; then
    return 1
fi

or use defaults:

from=${1:-0}
to=${2:-255}
ibuprofen
  • 2,890