I am trying to make a function in bash that gets a parameter and based on that parameter it colors the text. Say colorText RED will color my text red. This is what I wrote so far but it says ./colorText: line 10: ${$1}dad: bad substitution
#!/bin/bash
RED="\033[31m"
GREEN="\033[0;32m"
YELLOW="\033[0;33m"
NC="\033[0m"
colorText () {
echo $1
echo -e "${$1}dad"
}
colorText $1
The last $1 is because I want to use the script file from my terminal.
CodePudding user response:
Try this:
$ cat tst.sh
#!/usr/bin/env bash
declare -A c
c["RED"]='31'
c["GREEN"]='32'
c["YELLOW"]='33'
c["BLACK"]='0'
colorText () {
printf '%s\n' "$1"
printf '\e[%sm%s\e[0m\n' "${c[$1]}" 'dad'
}
colorText "$1"
See also:
CodePudding user response:
So check if $1
is equal to RED, if it is, output $RED
, repeat for every color. You can just switch on the color number.
case "$1" in
RED) n=31; ;;
GREEN) n=32; ;;
YELLOW) n=33; ;;
esac
echo -e "\033[${n}m"