Skip to content

Instantly share code, notes, and snippets.

@mariuscucuruz
Created February 15, 2024 15:03
Show Gist options
  • Save mariuscucuruz/fc9353f28583b57436f92a51fcae2761 to your computer and use it in GitHub Desktop.
Save mariuscucuruz/fc9353f28583b57436f92a51fcae2761 to your computer and use it in GitHub Desktop.
BASH: assign CLI positional argument to local variables
#!/bin/bash
### assign variables from CLI (posibional arguments)
first_user_arg="$1"
second_user_arg="$2"
third_user_arg="$3"
### have a default value to fallback on:
first_user_arg=${first_user_arg:-"default 1st value"}
### check if IS set:
if [[ -n "$second_user_arg" ]]; then
echo "Received $second_user_arg as the 2nd argument."
else
# fallback when $second_user_arg is not set
second_user_arg=${second_user_arg:-"default 2nd value"}
fi
### check if NOT exists:
if [[ -z $third_user_arg ]]; then
# echo "Defaulting to fallback for 3rd arg"
third_user_arg=("default 3rd value")
fi
### using variables
echo "The variables:
1st var: $first_user_arg
2nd var: $second_user_arg
3rd var: $third_user_arg
done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment