Terminal Takeaway πŸ₯‘

β€œArrays” in POSIX

POSIX Shell doesn’t have arrays but it does have β€œan array”… kind of. :stuck_out_tongue:

You can use the tools for managing arguments in semi-familiar ways to how arrays are managed in BASH. Each function has it’s own arguments too so each one has it’s own β€œarray”.

Play in terminal:

# Set arguments (do this first if playing in terminal)
set Setting 5 new array "elements here"

# Append an argument
set -- "$@" "and 1 more"

# Print number of arguments
echo $#

# Print all arguments (argument spaces and separator spaces are separate)
echo $@

# Print all arguments (spaces are ambiguous)
echo $*

# Print the 2nd argument
# Note: After $9 braces should be used to assure cross shell compatibility, ie: ${10}
echo $2

# Remove 2 arguments from the beginning
shift 2

# Remove 2 arguments from the end using rev
set -- $(rev <<< "$@")
shift 2
set -- $(rev <<< "$@")

# Remove 2 arguments from the end cycling through a loop
for i in $(seq 1 $#); do
	[ "$i" -le $(($# - 2)) ] && set -- "$@" "$1"
	shift
done

# Remove all arguements
shift $#

# Loop through all arguments
for Arg do
	echo "$Arg"
done