Search code examples
functionshellvariableswhiptail

Shell script function with global variable


yesterday I got a very easy task, but unfortunatelly looks like i can't do with a nice code.

The task briefly: I have a lot of parameters, that I want to ask with whiptail "interactive" mode in the installer script.

The detail of code:

#!/bin/bash

address="192.168.0.1" # default address, what the user can modify
addressT="" # temporary variable, that I want to check and modify, thats why I don't modify in the function the original variable
port="1234"
portT=""
... #there is a lot of other variable that I need for the installer

function parameter_set {
    $1=$(whiptail --title "Installer" --inputbox "$2" 12 60 "$3" 3>&1 1>&2 2>&3) # thats the line 38
}

parameter_set "addressT" "Please enter IP address!" "$address" 
parameter_set "portT" "Please enter PORT!" "$port"

But i got the following error:

"./install.sh: line: 38: address=127.0.0.1: command not found"

If I modify the variable to another (not a parameter of function), works well.

function parameter_set {
    foobar=$(whiptail --title "Installer" --inputbox "$2" 12 60 "$3" 3>&1 1>&2 2>&3)
    echo $foobar
}

I try to use global retval variable, and assign to outside of the function to the original variable, it works, but I think it's not the nicest solution for this task.

Could anybody help me, what I do it wrong? :)

Thanks in advance (and sorry for my bad english..), Attila


Solution

  • It seems that your whiptail command is not producing anyoutput because of the redirections. So the command substitution leaves the value empty. Try removing them. Also it's better to save the new value to a local variable first:

    parameter_set() {
        local NAME=$1
        local NEWVALUE=$(whiptail --title "Installer" --inputbox "$2" 12 60 "$3")
        export $NAME="$NEWVALUE"
    }