Skip to content

Instantly share code, notes, and snippets.

@sudoforge
Last active June 30, 2024 17:42
Show Gist options
  • Save sudoforge/13a9a702f0e23c456e37b0e007914460 to your computer and use it in GitHub Desktop.
Save sudoforge/13a9a702f0e23c456e37b0e007914460 to your computer and use it in GitHub Desktop.
A few different ways to grab input in a bash script.
#!/usr/bin/env bash
# assign "$1" and "$2", which are the first and second positional arguments,
# as items 0 and 1 in the `arr` array.
arr=("$1" "$2")
printf "\n\nthe final values are: %s\n" "${arr[*]}"
#!/usr/bin/env bash
# Prompt the user for some information, and add the input to an array.
# It'd be a good idea to perform validation on the provided input, which
# we do not do below in order to keep the example simple.
declare -a arr
read -p "What is your username? " -r username
arr+=("$username")
read -p "What is your favorite color? " -r color
arr+=("$color")
printf "\n\nthe final values are: %s\n" "${arr[*]}"
#!/usr/bin/env bash
# A bit more advanced now, we're going to let the user add any number of values
# to the array by using a loop.
declare -a arr
# present a introductory prompt to the user
echo "enter values, one on each line. Ctrl+D or a blank entry exits."
while read -p "add value: " -r value || printf "\n" ; do
# if the input is empty, stop prompting for a value
if test -z "$value"; then
break
fi
# append the user's input to an array
arr+=("$value")
done
printf "\n\nthe final values are: %s\n" "${arr[*]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment