Skip to content

Instantly share code, notes, and snippets.

@mike-clark-8192
Forked from mevanlc/install_z_sh.sh
Created February 24, 2024 11:23
Show Gist options
  • Save mike-clark-8192/801e385f6345003469ff7c3abac95430 to your computer and use it in GitHub Desktop.
Save mike-clark-8192/801e385f6345003469ff7c3abac95430 to your computer and use it in GitHub Desktop.
Helper script to install z.sh (jump around) - https://github.com/rupa/z
#!/bin/sh
SOURCE_URL="https://raw.githubusercontent.com/rupa/z/master/z.sh"
OUTPUT_LOC="$HOME/.z.sh"
usage_doc="Usage: $0 [-h] [-u url] [-o file]
-h this help
-u <url> download from <url>
default: $SOURCE_URL
-o <file> download to <file>
default: $OUTPUT_LOC
-f force overwrite of existing file
-y do not prompt for adding to rcfile"
main() {
parse_args "$@"
do_download
ask_edit_rcfile
}
do_download() {
if [ -z "$FORCE_OVERWRITE" ]; then
[ -f "$OUTPUT_LOC" ] && err_exit "output file already exists: $OUTPUT_LOC"
else
rm -f "$OUTPUT_LOC" || err_exit "error removing existing file: $OUTPUT_LOC"
fi
if [ -x "$(command -v wget)" ]; then
wget -qO "$OUTPUT_LOC" "$SOURCE_URL" || err_exit "wget failed"
elif [ -x "$(command -v curl)" ]; then
curl -so "$OUTPUT_LOC" "$SOURCE_URL" || err_exit "curl failed"
else
err_exit "$0 requires curl or wget to be installed"
fi
[ -f "$OUTPUT_LOC" ] || err_exit "could not create file: $OUTPUT_LOC"
echo "Created: $OUTPUT_LOC"
}
add_to_rcfile() {
if ! echo "source '$OUTPUT_LOC'" >>"$rcfile"; then
err_exit "Could not add to $rcfile"
fi
}
ask_edit_rcfile() {
sh_name=$(basename "$SHELL")
[ "$sh_name" = "bash" ] && rcfile="$HOME/.bashrc"
[ "$sh_name" = "zsh" ] && rcfile="$HOME/.zshrc"
if [ -z "$rcfile" ]; then
echo "Could not determine rcfile for $sh_name"
return
fi
if grep -q "source '$OUTPUT_LOC'" "$rcfile"; then
echo "Already in $rcfile"
return
fi
if [ -z "$FORCE_RCFILE" ]; then
printf "Add $OUTPUT_LOC to %s? [y/n] " "$rcfile"
read -r yn
case $yn in
[Yy]*) add_to_rcfile "$rcfile" ;;
*) return ;;
esac
fi
add_to_rcfile "$rcfile"
}
parse_args() {
while getopts "hfyu:o:" opt; do
case $opt in
u) SOURCE_URL="$OPTARG" ;;
o) OUTPUT_LOC="$OPTARG" ;;
f) FORCE_OVERWRITE=1 ;;
y) FORCE_OVERWRITE=1 && FORCE_RCFILE=1 ;;
h) usage && exit 0 ;;
*) usage ;;
esac
done
}
usage() { echo "$usage_doc" >&2; }
err_exit() {
echo "Error: $1" >&2
exit "${2:-1}"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment