scripts/url.shortme.sh

89 lines
2.1 KiB
Bash
Raw Permalink Normal View History

2020-03-11 16:08:44 +01:00
#!/bin/sh
# .. vim: foldmarker=[[[,]]]:foldmethod=marker
# This script will try to:
## Get first argument
## Or get clipboard content if no argument
## Send this data to an URL shortener
## Print the short url to stdout
## Or put it in the clipboard if no argument was given
# Vars [[[
2020-03-12 07:20:40 +01:00
debug=false
2020-03-11 16:48:35 +01:00
flag_clipboard=false
flag_inline=false
2020-03-11 16:08:44 +01:00
2020-03-11 16:38:05 +01:00
null_service_url="https://null.101010.fr"
2020-03-11 16:08:44 +01:00
## Colors [[[
c_redb='\033[1;31m'
c_magentab='\033[1;35m'
c_reset='\033[0m'
## ]]]
# ]]]
# Function to print a debug message [[[
debug_message() {
_message="${1}"
[ "${debug}" = "true" ] && printf "${c_magentab}%-6b${c_reset}\n" "DEBUG ${_message}"
}
# ]]]
2020-03-11 16:08:44 +01:00
# Verify argument [[[
case "$#" in
0 )
2020-03-11 16:48:35 +01:00
flag_clipboard=true
debug_message " Verify arg: No argument was given, try to use clipboard."
2020-03-11 16:08:44 +01:00
;;
1 )
2020-03-11 16:48:35 +01:00
flag_inline=true
debug_message " Verify arg: One argument was given, use it."
2020-03-11 16:08:44 +01:00
;;
* )
printf "${c_redb}%b${c_reset}\n" "Error: Expect one argument or a content in clipboard."
exit 1
;;
esac
# ]]]
2020-03-11 16:36:06 +01:00
# Get URL to be shortened [[[
# Try to get URL from first argument
2020-03-11 16:48:35 +01:00
if [ "${flag_inline}" = "true" ]; then
2020-03-11 16:36:06 +01:00
url_to_short="${1}"
fi
# Try to get URL from clipboard
2020-03-11 16:48:35 +01:00
if [ "${flag_clipboard}" = "true" ]; then
2020-03-11 18:35:25 +01:00
url_to_short=$(xclip -out -selection clipboard)
2020-03-11 16:36:06 +01:00
fi
debug_message " Get URL: URL to be shortened: ${url_to_short}"
2020-03-11 16:36:06 +01:00
# ]]]
# Ensure the URL wasn't already shortened [[[
if printf -- '%s' "${url_to_short}" | grep -q -E -- "${null_service_url}"
then
printf "${c_redb}%b${c_reset}\n" "Error: The url to be shortened (${url_to_short}) already seems to comes from the 0x0 service (${null_service_url})."
exit 1
fi
# ]]]
2020-03-11 16:36:06 +01:00
2020-03-11 16:38:05 +01:00
# shorten URL
result=$(curl -sF"shorten=${url_to_short}" "${null_service_url}")
2020-03-11 16:59:09 +01:00
# Manage the result [[[
## If the URL should simply be printed to stdout
if [ "${flag_inline}" = "true" ]; then
debug_message " Manage result: Print the result on stdout:"
2020-03-11 16:59:09 +01:00
printf "%b\n" "${result}"
fi
# If the URL should remplace the previous content of the clipboard
if [ "${flag_clipboard}" = "true" ]; then
debug_message " Manage result: Put the result in clipboard."
2020-03-11 16:59:09 +01:00
echo "${result}" | xclip -rmlastnl -selection clipboard
fi
# ]]]
2020-03-11 16:08:44 +01:00
exit 0