Created
March 8, 2023 14:23
-
-
Save codebymikey/7bd7003efc00398c89fb4121e0dba326 to your computer and use it in GitHub Desktop.
Provide a script that parses a command and prints out its options and positional arguments.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Define variables for holding positional arguments and options | |
POSITIONAL=() | |
OPTIONS=() | |
# Loop through all arguments passed to the script | |
while [[ $# -gt 0 ]] | |
do | |
key="$1" | |
# Check if the argument is an option or a positional argument | |
if [[ "$key" == "--" ]] | |
then | |
# If -- is encountered, stop parsing options and treat remaining arguments as positional | |
shift | |
POSITIONAL+=("$@") | |
break | |
elif [[ ${key:0:2} == "--" ]] | |
then | |
# Handle options with a value provided using --option value or --option=value syntax | |
if [[ "$key" =~ "=" ]] | |
then | |
option="${key%=*}" | |
value="${key#*=}" | |
elif [[ "$2" != "" && ${2:0:2} != "--" ]] | |
then | |
option="$key" | |
value="$2" | |
shift | |
else | |
# Handle boolean options | |
option="$key" | |
value="" | |
fi | |
# Save the option to the OPTIONS array | |
if [[ -z "$value" ]] | |
then | |
OPTIONS+=("$option") | |
else | |
OPTIONS+=("$option=$value") | |
fi | |
else | |
# Save the positional argument to the POSITIONAL array | |
POSITIONAL+=("$key") | |
fi | |
# Shift to the next argument | |
shift | |
done | |
# Print out the positional arguments and options in an easy to understand format | |
echo "Positional arguments:" | |
for arg in "${POSITIONAL[@]}" | |
do | |
echo " * $arg" | |
done | |
echo "Options:" | |
for option in "${OPTIONS[@]}" | |
do | |
echo " * $option" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment