Skip to content

Instantly share code, notes, and snippets.

@cannandev
Last active June 28, 2022 00:57
Show Gist options
  • Save cannandev/d428d3d41e515b5346437fbbdd5296d0 to your computer and use it in GitHub Desktop.
Save cannandev/d428d3d41e515b5346437fbbdd5296d0 to your computer and use it in GitHub Desktop.
Slugify a string in bash and copy it to the clipboard. Great for blog filenames.
# Define the slugify function.
slugify () {
# Convert the string into a slug and assign it to a variable.
slug="$(echo "$1" | iconv -t ascii//TRANSLIT | sed -r s/[~\^]+//g | sed -r s/[^a-zA-Z0-9]+/-/g | sed -r s/^-+\|-+$//g | tr A-Z a-z)"
# Copy the passed variable to system clipboard.
echo "$slug" | pbcopy
# Show user the slug and status.
echo "$slug was copied to your clipboard."
}
# Define the welcome function.
welcome () {
# Greet system user and prompt for a string.
echo "Hi, "$USER"! Please enter the string you want to slugify:"
# Read the string into a variable.
read string
# If the string is empty, check prompt again
if [ -z "$string" ]
then echo "String was empty. Try again."
# Call the slugify function, passing the slug as a parameter. Double quote to avoid misparsing.
else slugify "$string"
fi
}
# Execute the welcome function.
welcome
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment