arch/pkg/de-p1st-installer/name-reference-test.sh

40 lines
1.0 KiB
Bash

#!/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 VAR=$1
if [ -z "$VAR" ]; then
echo "$2"
read -r VAR || return $?
fi
# check string length to be greater than zero!
if [ "${#VAR}" -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"