#!/usr/bin/env bash # From: https://github.com/mchav/with/blob/master/with # Date: 20-08-2016. # Web: https://bitbucket.org/lbesson/bin/src/master/with.sh # # with tool # # Usage: with # Opens an interactive shell instance that automatically prefixes all subsequent commands with program name # # Licence: MIT Licence (http://lbesson.mit-license.org). version="0.2" # Initialize history file touch /tmp/with_history function finish { # Save history to bash history if [ -f ~/.bash_history ]; then cat /tmp/with_history >> ~/.bash_history fi # rm -vf /tmp/with_history } # thanks to /u/Vaphell drop_with() { if [ ${#prefix[@]} -gt 1 ] then prefix=( "${prefix[@]:0:${#prefix[@]}-1}" ) else exit 0 fi } add_with() { # separate into white space # FIXME: foo "bar baz" should add two elements not one IFS=' ' read -r -a parse_array <<< "$@" prefix=( "${prefix[@]}" "${parse_array[@]}" ) } run_with() { while IFS="" read -r -e -d $'\n' -p "$pmpt> " options; do history -s "$options" > /dev/null 2>&1 curr_command="$(echo "$options" | { read -r first rest ; echo "$first" ; })" case $curr_command in "" ) # null case: run prefix ${prefix[*]} ;; "-" ) # remove with drop_with pmpt="${prefix[*]}" ;; +* ) # nesting withs parsed=${options#"+"} add_with "$parsed" pmpt="${prefix[*]}" ;; :* ) # shell command parsed=${options#":"} if [ "$parsed" = "q" ]; then exit 0 fi IFS=' ' read -r -a parsed_array <<< "$parsed" echo "${parsed_array[@]}" >> /tmp/with_history eval "${parsed_array[@]}" ;; * ) # prepend prefix to command echo "${prefix[*]} ${options}" >> /tmp/with_history eval "${prefix[*]} ${options}" esac done } trap finish exit declare -a prefix prefix=( "$@" ) pmpt=${prefix[*]} helpmsg="Usage: with " if [ -z "$*" ]; then echo "Missing arguments." echo $helpmsg exit 1 fi if [ "$*" == "--help" ]; then echo $helpmsg exit 0 fi if ! type "$1" > /dev/null 2>&1; then echo "error: Program" "$1" "is not installed" exit 1 fi while true ; do run_with done