Last active
April 16, 2016 15:08
-
-
Save t-mw/6c5de54102554d241b00c888c982440c to your computer and use it in GitHub Desktop.
interact.bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# make commands interactive, essentially a bash version of http://thorstenball.com/fzz/. | |
# to use, copy to ~/.bash_profile or similar. requires ncurses. | |
# e.g. for an interactive `git grep`: | |
# interact git grep {{}} | ... | |
interact() { | |
# for printing ui create fd pointing to tty, | |
# in case stdout is redirected | |
exec 3> /dev/tty | |
local cmd="$@" | |
local input_locator="{{}}" | |
local input="" | |
local result="" | |
# save current terminal output | |
tput smcup >&3 | |
echo -n ">> $input" >&3 | |
while true; do | |
read -rsn 1 char | |
if [[ $char == $'\177' ]]; then | |
# on backspace | |
input="${input%?}" | |
elif [[ $char == "" ]]; then | |
# on return | |
break | |
elif [[ $char == $'\e' ]]; then | |
# on escape | |
return "" | |
else | |
input+="$char" | |
fi | |
# replace input locator with user input and evaluate command | |
result=$(eval ${cmd/$input_locator/\"$input\"}) | |
# print input on first line of terminal followed by command output | |
tput clear >&3 | |
echo -n ">> $input" >&3 | |
tput sc >&3 | |
tput cud1 >&3 | |
# trim command output to screen | |
local lines=$(tput lines) | |
local cols=$(tput cols) | |
echo -n "$(head -n $((lines-1)) <<< "$result" | cut -c-$cols)" >&3 | |
tput rc >&3 | |
done | |
# restore previous terminal output | |
tput rmcup >&3 | |
echo "$result" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment