0

I write a basic script which it has colourful lines in it.

#!/bin/bash

g="\e[32m"
_0="\e[0m"

printf "$g name $_0"

The script runs normally but at shellcheck.net I got this message: Don't use variables in the printf format string.

Another problem when I convert my script to #!/bin/sh my script doesn't run correctly, giving this output:

\e[32m name \e[0m

I used echo -e but this time sh said that -e wasn't supported. How do I write a common line of code to solve this problem? Thank you.

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
  • This is almost https://unix.stackexchange.com/q/205497/5132 again. – JdeBP Dec 17 '19 at 14:08
  • Thanks. Yes it works with ```bash``` but not with ```sh``` Is there a way that work with both? –  Dec 17 '19 at 14:30

1 Answers1

2

You can use this, will work either on bash or sh:

#!/bin/bash

# \e not supported by POSIX; use \033 (octal) instead.
g=$(printf '\033[32m')
_0=$(printf '\033[0m')

printf '%s name %s foo' "$g" "$_0"
schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
  • Thanks that's the anwser I was looking for! Plus, why shellcheck.net says```Don't use variables in the printf format string.``` Is there a solid reason? –  Dec 17 '19 at 14:40
  • 1
    @AhmetMehmet It makes it very difficult to print strings contains backslashes and percentage signs for starters. – Kusalananda Dec 17 '19 at 14:55
  • 1
    To print to a variable in `bash`, use e.g. `printf -v _0 '\033[0m'`. No need for the command substitution. – Kusalananda Dec 17 '19 at 14:56
  • Thanks I see. Is there a site to show all characters octal forms like \033 I find different things? –  Dec 17 '19 at 15:57
  • 1
    You can check [here](http://www.asciitable.com/) – schrodingerscatcuriosity Dec 17 '19 at 16:15
  • 1
    Or use `man ascii`. And https://unix.stackexchange.com/q/371827/5132 gives one reason that this answer is as it is. – JdeBP Dec 18 '19 at 12:32