bash scripting practice: batch add users
#bash #scripting #bashsyntax #UofTBootCamp #homework
Takeaways
- quotes around the
array
in afor
loop is best practice:
Without them, the
for
loop will break up the array by substrings separated >by any spaces within the strings instead of by whole string elements within >the array. ie: if you haddeclare -a arr=("element 1" "element 2" "element 3")
, >thenfor i in ${arr[@]}
would mistakenly iterate 6 times since each string >becomes 2 substrings separated by the space in the string, whereas fori in >"${arr[@]}"
would iterate 3 times, correctly, as desired, maintaining each >string as a single unit despite having a space in it.
- you can only capture with
echo
. Usingreturn
is the same asexit
(so you can only capture the exit code)
Syntax Quickies
quick init + iteration
read -a arr <<< "one two three"
for i in ${arr[@]}
do
echo $i
done
- access elements
passing multiple arrays as arguments
`takesaryas_arg()
{
declare -a argAry1=(“${!1}”)
echo “${argAry1[@]}”
declare -a argAry2=(“${!2}”)
echo “${argAry2[@]}”
}
trywithlocalarys()
{
# array variables could have local scope
local descTable=(
“sli4-iread”
“sli4-iwrite”
“sli3-iread”
“sli3-iwrite”
)
local optsTable=(
“—msix —iread”
“—msix —iwrite”
“—msi —iread”
“—msi —iwrite”
)
takesaryasarg descTable[@] optsTable[@]
}
trywithlocal_arys`