godblessfq
godblessfq

Reputation: 218

Bash variable substitution in a function

I have a function read_command defined as:

function read_command {
    local __newline __lines __input __newstr __tmp i;
    exec 3< "$*";
    __newline=$'\n';
    __lines=();
    while IFS= read <&3 -r __line && [ "$__line" != '####' ]; do
        echo "$__line";
        __lines+=("$__line");
    done
    while IFS= read <&3 -r __line && [ "$__line" != '####' ]; do
        read -e -p "${__line#*:}$PS2" __input;
        local ${__line%%:*}="$__input";
    done
    __command="";
    for i in "${__lines[@]}"; do
        __tmp=$(echo "${i}");
        __command="${__command} ${__newline} ${__tmp}";
    done
    echo -e "$__command";
}

In the current directory there is a file named "test", with the following content:

greet ${a:-"Bob"} 
greet ${b:-"Jim"}
####
a: name of friend a
b: name of friend b
####

In the terminal, the command executed is

read_command test

With no input, I am expecting the output of the last statement to be:

greet Bob
greet Jim

But what I get is:

greet ${a:-"Bob"}  
greet ${b:-"Jim"}

What is wrong here?

Edit: As suggested by David, adding eval works in some cases except the following one.

j=1;i="export DISPLAY=:0 && Xephyr :${j}&";k=$(eval echo "$i");
echo $k

export DISPLAY=:0

I am expecting k to be "export DISPLAY=:0 && Xephyr :1&", what's wrong here? Edit: I tried with the following

k=$(eval "echo \"$i\"")

This is the link to the script I am working on. https://gist.github.com/QiangF/565102ba3b6123942b9bf6b897c05f87

Upvotes: 1

Views: 409

Answers (1)

Matei David
Matei David

Reputation: 2362

During the first while loop, in echo "$__line", you have __line='greet ${a:-"Bob"}'. When you try to print that, Bash won't be expanding ${a:-"Bob"} into Bob. (Even if you remove the quotes around $__line this won't happen.) To get that effect, you need to add eval, as in, e.g., eval echo "$__line". Unfortunately eval comes with its can of worms, you have to start worrying about interactions between quoting levels and such.

Upvotes: 2

Related Questions