Bash script function that changes the value of a variable
3
votes
2
answers
1635
views
I'd like to make a function for a BASH script that changes the value of one of its arguments, that is a variable. The function that I did is:
chck_rgx () { # Checks that the given name for a user/group fulfills the regex. The function's parameters are
# * $1: kind of name to check: username, hostname, etc.
# * $2: variable whose value to check if meets the requirements.
local rgx_hostname='^[a-z][a-zA-Z0-9_-]+$' ;
local rgx_inputbox_hostname="The hostname you just submitted isn't a valid name. Try with another name."
local rgx_username='^[a-z][a-z0-9_-]+$' ;
local rgx_inputbox_username="The username you just submitted isn't a valid name. Try with another name." ;
eval rgx_name="\$rgx_$1" ;
eval rgx_inputbox="\$rgx_inputbox_$1" ;
eval name_ch="\$$2" ;
while [[ ! $name_ch =~ $rgx_name ]] ; do
dialog --backtitle "$backtitle_var" \
--title "Wrong $1 submitted" --clear \
--inputbox "$rgx_inputbox" 0 0 2> name-ch ;
name_ch=$(cat name-ch) ;
rm name-ch ;
done
chckd_var="$name_ch" ;
}
Then in some part of the script there is a dialog box asking you to insert a name and then this function checks if the given name is a valid name. For instance,
dialog --backtitle "$backtitle_var" \
--title "Submit the username" --clear \
--inputbox "Which username do you want?" 0 0 2> user-name ;
user_name=$(cat user-name) ;
chck_rgx username user_name ;
user_name=$chckd_var ;
The problem I have is that the "output" of my function, the value I have now, is not in the same variable I used in the first place. I have to assign the value of the "output" of my function ($chckd_var) to the variable that I inserted as an argument in the function (user_name). What I want to do is that the function changes the value of the global variable user_name (or whatever other variable).
Also, I'd like to know if there's a way to get the output of a dialog inputbox directly in a variable; not in a file.
I'm fairly new to BASH scripts, so perhaps the answer is quite simple. Anyway, I've been looking for this on the web and haven't found the answer.
Asked by ctafur
(59 rep)
Jul 28, 2015, 09:48 PM
Last activity: Apr 4, 2023, 12:00 PM
Last activity: Apr 4, 2023, 12:00 PM