[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: OT: coloured text?



On Sun, Jan 07, 2024 at 07:40:28PM +0100, Hans wrote:
> How can I get coloured text output in a shell script? 

https://mywiki.wooledge.org/BashFAQ/037

> Debian is using "dash" and not "bash", if I am correct,

Debian installs BOTH of them by default.

Also by default, the /bin/sh symbolic link points to dash, rather
than to bash.  But this should not matter to you.

> shebang line :!/bin/sh it is using dash, am I correct?

You mean #!/bin/sh of course.  When selecting a shebang, you do so
based on which shell's syntax and features you are using in your
script.

If you're using bash syntax, then your shebang should be #!/bin/bash .

If you are NOT using any bash syntax or features, but strictly POSIX sh,
then you may use #!/bin/sh as your shebang.

The shebang tells the kernel which shell to execute to interpret your
script.  So, you match it up to whichever shell you're writing for.

> If I want coloured text, which shell do I have to use and what is the syntax 
> then within the shell script?

The wiki page has examples for both Bourne shell (which is a subset of
POSIX sh) and bash.

The approach I would take depends on how you're using colors in your
script.  Are you only doing them inside one function which writes an
error message and exits?  In this case, you might just use the tput
commands interleaved with printf or echo commands, as shown in the
first example.

If you're going to write *lots* of colored lines, you might choose to
store the escape sequences in global variables, and use them within
the function(s) that write colored messages.  Something like:

Program='MyProgram'
Red=$(tput setaf 1)
Normal=$(tput sgr0)
error() {
    printf 1>&2 '%s: %s%s%s\n' "$Program" "$Red" "$*" "$Normal"
}

All of this syntax is POSIX sh compatible, by the way.


Reply to: