Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parameter substitution inside function

Tags:

bash

shell

I need to set a default value (y) when the user hits enter in read

validate() {
    local validated=false
    while [ "$validated" != "true" ]; do
            read -p "$1 " $2
            $2=${2:-y}
            if [[ "$2" == "y" || "$2" == "n" ]]; then
                    validated=true
            fi
    done
}

When I run this function with validate "text" test and skip the read with enter, the error test=test: command not found appears. How can I use the substitution with function arguments?

like image 815
Coli Avatar asked Mar 14 '26 04:03

Coli


1 Answers

To write a value to a variable with a dynamic name, you can use printf -v "$name" "$value". This should be closer to what you want, though I suspect some further confusion and follow-up questions:

validate() {
    local message=$1
    local out=$2
    local validated=false answer

    while [ "$validated" != true ]; do
        read -p "$message " answer
        answer=${answer:-y}
        if [[ "$answer" == "y" || "$answer" == "n" ]]; then
            validated=true
        fi
    done

    printf -v "$out" "$answer"
}
like image 53
janos Avatar answered Mar 16 '26 04:03

janos