#!/usr/bin/env bash ############# # Variables # ############# # Define formatting variables fb="$(tput bold)" ; readonly fb fr="$(tput sgr0)" ; readonly fr ############# # Functions # ############# display_usage() { help_msg="Usage: '${0}' [ex_option] ex_dir Purpose: Select a random object from a provided directory and place its path on the system clipboard. Options: -o, --open Open last selected random object before quitting with default application. Requires: xclip command line interface to X selections (clipboard)" echo "${help_msg}" } # Verify object exists and is a directory val_extant_dir() { local to_test to_test="${1}" [[ -d "${to_test}" ]] ; echo "${?}" } # Parse arguments parse_args() { local parsed_args inv_ents pass_or_fail parsed_args="$(getopt \ -n "${0##*/}" \ -o ho \ --long help,open \ -- "${@}")" inv_ents="${?}" # Check for invalid entries if [[ "${inv_ents}" -ne 0 ]]; then echo '' display_usage exit 1 fi # Set positional parameters using parsed argument string eval set -- "${parsed_args}" # Evaluate options while true; do case "${1}" in '-h' | '--help') display_usage exit 0 ;; '-o' | '--open') o_on='true' shift ;; '--') ## End of options shift break ;; esac done # Evaluate argument pass_or_fail="$(val_extant_dir "${1}")" if [[ "${pass_or_fail}" -eq 0 ]]; then entd_dir="${1%/}" # Remove trailing slash if present else err_msg='\nInvalid directory path provided. Try again.' echo -e "${err_msg}" 1>&2 exit 1 fi } # Run initialization checks run_init_cks() { local err_msg # Verify script being run from desktop environment if ! [[ "${XDG_CURRENT_DESKTOP}" ]]; then err_msg='\nA desktop environment must be available to ' err_msg+='use this script.' echo -e "${err_msg}" 1>&2 exit 1 fi # Verify that command is installed if ! command -v 'xclip' > '/dev/null' 2>&1; then # Prompt user to install command and exit err_msg="\nInstall ${fb}xclip${fr} before running " err_msg+='the script again.' echo -e "${err_msg}" 1>&2 exit 1 fi } # Define starting point for execution of the program main() { parse_args "${@}" run_init_cks # Determine number of objects for provided directory num_of_objs="$(find "${entd_dir}" -mindepth 1 -maxdepth 1 ! -name '.*' | wc -l)" # Create object paths associated array declare -a obj_paths mapfile -t obj_paths < \ <(find "${entd_dir}" -mindepth 1 -maxdepth 1 ! -name '.*') # Initiate random object path generation loop prompt='Enter any key to continue or q to quit: ' while echo '' && read -p "${prompt}" -r choice; do if [[ "${choice}" == 'q' ]]; then if [[ "${o_on}" ]]; then xdg-open "${obj_paths[${ran_num}]}" > '/dev/null' 2>&1 fi break else ran_num="$(shuf -i 0-"$(( num_of_objs - 1 ))" -n 1)" output="\nChosen random index: ${ran_num}" output+="\n${obj_paths[${ran_num}]}" echo -e "${output}" fi done # Save last object path to clipboard echo "${obj_paths[${ran_num}]}" | xclip -selection c } ########### # Program # ########### main "${@}" # Start program exit 0 # Exit script with successful exit status