#!/bin/bash # source: https://stackoverflow.com/a/52678279/6334421 # A variable can be assigned the nameref attribute using the -n option # to the declare or local builtin commands (see Bash Builtins) to create # a nameref, or a reference to another variable. This allows variables to # be manipulated indirectly. function text_input { # If variable of name $1 is zero, then ask user for input. # Only one line user input is allowed. # User input must not be empty. # # $1: variable name to store input to # $2: text to display (e.g. "Enter hostname:") if [ -z "$1" ] || [ -z "$2" ]; then echo "text_input requires two args!"; return 1 fi local -n ptr=$1 || return $? if [ -z "$ptr" ]; then echo "$2" read -r ptr || return $? fi # check string length to be greater than zero! if [ "${#ptr}" -lt 1 ]; then echo "text_input must not be empty!"; return 1; fi } text_input foo "Enter something funny:" echo "Input: $foo" bar="" text_input bar "Enter something even funnier:" echo "Input: $bar"