AzureOrange404
AzureOrange404

Reputation: 11

How can I cycle through an array in bash while also passing an argument to the script?

I have the following bash script I want to use as my "standard browser" with xdg-open.

It should prompt dmenu for me to choose the browser to open the url in.

Now xdg-open passes the url as an argument to the program (I suppose) and as I'm cycling through an array of browsers using the @ symbol, it confuses this one with the argument (url) and errors on the dmenu command.

Is there a workaround to this problem or am I doing something completely wrong? --This problem was solved

#!/usr/bin/env bash

set -euo pipefail
_path="$(cd "$(dirname "${BASH_SOURCE[0]}")" && cd "$(dirname "$(readlink "${BASH_SOURCE[0]}" || echo ".")")" && pwd)"
if [[  -f "${_path}/_dm-helper.sh" ]]; then
  # shellcheck disable=SC1090,SC1091
  source "${_path}/_dm-helper.sh"
else
  # shellcheck disable=SC1090
  echo "No helper-script found"
fi

# script will not hit this if there is no config-file to load
# shellcheck disable=SC1090

source "$(get_config)"

main() {

if [ -t 0 ]
then
    _url=$1
else
    read _url
fi

_browser=$(printf '%s\n' "${!browsers[@]}" | sort | ${DMENU} 'Select browser: ') # "$@") ## Thx to @jhnc
_command=${browsers[${_browser}]}


if [[ -n ${_url} ]];then
        $_command $_url
fi

}

[[ "${BASH_SOURCE[0]}" == "${0}" ]] && main "$@"

(get config) loads the dmenu command: DMENU=dmenu -i -l 20 -p as well as the array of browsers:

declare -A browsers
browsers[brave]="brave-browser"
browsers[firefox]="firefox"
browsers[opera]="opera"
browsers[badwolf]="badwolf"

from my config file.

Originally if i ran xdg-open "https://" or if I clicked on a url in some other program, brave was opened with on that site.

Now after xdg-settings set default-web-browser dmenu-script.desktop with the following .desktop file:

[Desktop Entry]
Version=1.0
Name=Dmenu Browser Script
GenericName=Web Browser
# Gnome and KDE 3 uses Comment.
Comment=Access the Internet
Exec=$HOME/.local/bin/dmenu-browser %U
StartupNotify=true
Terminal=false
Icon=brave-browser
Type=Application
Categories=Network;WebBrowser;
MimeType=application/pdf;application/rdf+xml;application/rss+xml;application/xhtml+xml;application/xhtml_xml;application/xml;image/gif;image/jpeg;image/png;image/webp;text/html;text/xml;x-scheme-handler/http;x-scheme-handler/https;x-scheme-handler/ipfs;x-scheme-handler/ipns;
Actions=new-window;new-private-window;

[Desktop Action new-window]
Name=New Window
Exec=$HOME/.local/bin/dmenu-browser

[Desktop Action new-private-window]
Name=New Incognito Window
Exec=$HOME/.local/bin/dmenu-browser --incognito

It only works if I execute xdg-open from my command line. (I modified the .desktop file of brave-browser, because I had no clue how to write one.)

Upvotes: 1

Views: 108

Answers (0)

Related Questions