Skip to content

Instantly share code, notes, and snippets.

@apfelchips
Last active February 11, 2024 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save apfelchips/001b4ffb22c0578220595623f5546107 to your computer and use it in GitHub Desktop.
Save apfelchips/001b4ffb22c0578220595623f5546107 to your computer and use it in GitHub Desktop.
url-open.sh - open links contained in .URL and .webloc files in your default browser
#!/bin/bash
# src: https://gist.github.com/apfelchips/001b4ffb22c0578220595623f5546107
# mkdir -p "$HOME/bin" && curl -L "https://git.io/JKGha" -o "$HOME/bin/url-open.sh" && chmod +x "$HOME/bin/url-open.sh" && url-open.sh
install_desktop_file(){
# MimeSpec: https://gitlab.freedesktop.org/xdg/shared-mime-info/-/blob/master/data/freedesktop.org.xml.in
# Desktop Entry Spec: https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s07.html
echo "creating .desktop entry"
cat << EOF > "${XDG_DATA_HOME:-$HOME/.local/share}/applications/url-open.desktop"
[Desktop Entry]
Type=Application
NoDisplay=true
Exec=url-open.sh %F
Name=Open URL
GenericName=.URL | .webloc File Opener
Comment=Open .URL | .webloc files in your default web browser.
Categories=Network
Icon=internet-web-browser
MimeType=application/x-mswinurl
Terminal=false
StartupNotify=false
EOF
update-desktop-database "${XDG_DATA_HOME:-$HOME/.local/share}/applications"
}
main(){
# .URL spec: http://www.lyberty.com/encyc/articles/tech/dot_url_format_-_an_unofficial_guide.html
# examples: https://github.com/beckus/WebShortcutSamples
for arg in "$@"; do
if ! [ -f "${arg}" ] && ! [ -r "${arg}" ]; then
echo "file: '${arg}' doesn't exist or isn't readable." 1>&2
continue
fi
if (echo "${arg}" | grep -iq '.url$') || (echo "${arg}" | grep -iq '.website$'); then
local url=$(awk -F "=" '/URL/ {printf $2}' "${arg}" | tr -d ' ')
elif (echo "${arg}" | grep -iq '.webloc$'); then
if command -v 'plutil' > /dev/null; then
plutil -convert xml1 "${arg}" && echo "plutil converted .webloc file to xml" 1>&2
fi
local url=$(cat "${arg}" | grep "string" | sed "s/<string>//" | sed "s/<\/string>//" | sed "s/ //" | awk '{$1=$1;print}')
else
echo "unknown filetype - skipping: ${arg}" 1>&2
continue
fi
if [ -z "$url" ]; then
echo "didn't find an url in file '${arg}'." 1>&2
continue
fi
if (command -v 'xdg-open' >/dev/null); then
# see: http://inglorion.net/software/detach/
echo "xdg-open ${url}" 1>&2
setsid xdg-open "${url}"
#nohup xdg-open "${url}"
elif (command -v 'open' >/dev/null); then
echo "open ${url}" 1>&2
open debug "$url"
else
echo "couldn't find open command" 1>&2
echo "url is: ${url}" 1>&2
fi
sleep 1
done
}
if [ -d "${XDG_DATA_HOME:-$HOME/.local/share}/applications/" ] && ! [ -f "${XDG_DATA_HOME:-$HOME/.local/share}/applications/url_open.desktop" ]; then
install_desktop_file
fi
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment