I want to define and get all the required variables that are passed to a function as parameters:
function explain_vars() {
echo "Explaining vars '$@':" >&2
for _var in "$@"; do
printf " $_var: '${!_var}'\n" >&2
done
printf "\n" >&2
}
function read_params() (
## Define local variables
_vars=(v1 v2 v3)
local ${_vars[@]}
## Read variables from input:
read ${_vars[@]} <<< "$@"
explain_vars "${_vars[@]}"
)
The read takes puts all parameters in the specified variables, default delimiter here is space. So if I pass different strings as second parameter, read will store only the first string in the second parameter, and all the rest to the following parameters:
$ read_params one "two dot one" "three" "four"
Explaining vars 'v1 v2 v3':
v1: 'one'
v2: 'two'
v3: 'dot one three four'
As we can see, variable v2 is not synchronized with given parameters anymore. Moreover, it fails at reading empty strings:
$ read_params one "" " " '' ' ' "two dot one" "three" "four"
Explaining vars 'v1 v2 v3':
v1: 'one'
v2: 'two'
v3: 'dot one three four'
By looping through the all-parameters variable $@ inside the function it is possible to distinguish variables:
function raw_params() (
echo "Explaining row parameters:"
for _v in "${@}"; do
printf " '$_v'\n"
done
)
$ raw_params one "" " " '' ' ' "two dot one" "three" "four"
Explaining row parameters:
'one'
''
' '
''
' '
'two dot one'
'three'
'four'
To me the read command offers benefit and quickness at defining, controlling and checking requested parameters that are passed to functions. However this works only for single and non-empty stringed parameters. Is it possible to read all different parameters in variables like the read command does, but respecting spaces and empty parameters? Or is there a better approach maybe?
man bash, Here Strings it says: "<<<word: Thewordundergoes brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal." (emphasis me). In other words you lose the quotes and with that parameter "grouping" you've expected and needed.readcannot be used in my case? Reading fromstdinwill also remove quotes.