I've got the following situation:
I'm writing a script that will read its parameters either from a config file (if exists and parameter present) or asks the user to input said parameter if it's not present.
Since I'm doing this for a handful of parameters I thought writing a function would be the way to go.
However, as far as I understand it, the function returns the result value by echo
ing it or by assigning it to a global variable. I do want to echo to the screen in the function though, so it'll have to be option two. So i tried this:
# parameters: $1=name of parameter, $2=user prompt, $3=value read from config.cfg function getParameter { # If the value couldn't be read from the config file if [ -z "$3" ]; then # Echo the prompt echo "$2" # Read the user input read parameter # If it's empty, fail if [ -z "$parameter" ]; then echo "Parameter $1 not found" exit # Else, try to assign it to $3 <---- This is where it fails else $3="$parameter" fi fi }
I call it like this:
getParameter "Database username" "Please enter database username" $database_username
The config.cfg
file is source
d before the function is called and $database_username
is one of the optional parameters there.
Now this obviously doesn't work. I can't assign to $3
and since I want the method to be generic, I can't do MY_VARIABLE=$parameter
either.
Does anyone have any suggestions how I can achieve all of the below:
- Get variable value from either
config.cfg
or read it from the user input - Do this in a generic fashion, i.e. don't repeat the above code (without a function) for each parameter