Skip to content

Instantly share code, notes, and snippets.

@dale3h
Last active December 4, 2018 21:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dale3h/f0e0665d68b5b1fc0ff0990ea24f43f6 to your computer and use it in GitHub Desktop.
Save dale3h/f0e0665d68b5b1fc0ff0990ea24f43f6 to your computer and use it in GitHub Desktop.
Ensure Alpine packages are installed and then run a command
#!/bin/bash
################################################################
## @usage pkg-x node=nodejs node /my/node-script.js "arg1" "arg2"
## @usage pkg-x expect,telnet=busybox-extras /path/to/telnet.sh "uptime"
## @description Ensure Alpine packages are installed and then run a command
## @license MIT
## @author Dale Higgs <@dale3h>
################################################################
packages="$1"
script="${@:2}"
logfile="$(basename $0).log"
function log() {
if [[ $# -gt 1 ]]; then
level="$1"
shift
else
level="INFO"
fi
echo "[$(date)] [$level] ${@}" >> $logfile
}
# Check for apk (Alpine Package Manager)
apk="$(command -v apk)" || { log "ERROR" "missing apk"; exit 0; }
# Loop through packages and install them if not found
IFS=',' read -ra packages <<< "$packages"
for package in "${packages[@]}"; do
IFS='=' read -r cmd pkg <<< "$package"
[[ -z "$pkg" ]] && pkg="$cmd"
[[ -n "$(command -v $cmd)" ]] \
|| { log "INFO" "installing package $pkg (for $cmd)"; $apk add --no-cache $pkg >> $logfile 2>&1; } \
|| { log "ERROR" "could not install package $pkg (for $cmd)"; exit 0; }
done
# If provided, run the command
if [[ $# -gt 1 ]]; then
$script
fi
@elRadix
Copy link

elRadix commented Dec 4, 2018

how to run this? I need this for hassio? would this work?
mainly to for my expect script to control telnet switches

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment