이형욱 이형욱 - 5 months ago 22
Bash Question

Shell script function parameter with double quote that ECHO command's SIGN

I'm developing some shell script. please help me

I want to highlight specific strings with FUNCTION like this.

#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}

echoWithColor "Hello everyone!"


this works, but I want to add some blank (space text) at end of line like

echo -n "Input your age : "; read AGE



[root@mycomputer scripts]# ./script.sh

Input your age : 9999


but

#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}

echoWithColor "-n Input your age : "; read AGE



[root@mycomputer scripts]# ./script.sh

Input your age :9999


Nope

.

#!/bin/bash
function echoWithColor(){
local InputString=${1}
tput bold;tput setaf 2 # make words color to bright green
echo ${InputString}
tput sgr0 # make words color to default
}

echoWithColor "-n \"Input your age : \""; read AGE



[root@mycomputer scripts]# ./script.sh

"Input your age :"9999


Escaping? Nope.

How can I add blank text at end of line?

Answer

This happens because you don't quote your variables:

var="    my value    "
echo $var without quotes   # writes: my value without quotes
echo "$var with quotes"    # writes:    my value     with quotes

Since you want to pass pass multiple strings to echo (both -n and Input your age), you should rewrite the function to take multiple arguments ("$@") instead of just one ($1), and then make sure to quote when using them:

#!/bin/bash
echoWithColor(){
    local InputStrings=( "$@" ) 
    tput bold;tput setaf 2   # make words color to bright green
    echo "${InputStrings[@]}"
    tput sgr0                # make words color to default
}

echoWithColor -n "Input your age: "

Now echoWithColor works exactly like echo, and preserves all spaces you pass to it.