Skip to content

Instantly share code, notes, and snippets.

@dapithor
Forked from postpostscript/ replify
Last active August 20, 2016 19:09
Show Gist options
  • Save dapithor/2d553293fb504dc27c2feb61634eca06 to your computer and use it in GitHub Desktop.
Save dapithor/2d553293fb504dc27c2feb61634eca06 to your computer and use it in GitHub Desktop.
replify - Create a REPL for any command
#!/bin/sh
command="${*}"
printf "Initialized REPL for [%s]\n" "$command"
printf "%s> " "$command"
read -r input
while [ "$input" != "" ];
do
eval "$command $input"
printf "\n%s> " "$command"
read -r input
done

HN Discussion

$ replify echo
Initialized REPL for [echo]
echo> "Hello, World!" 
Hello, World!

echo> "It works!"
It works!

$ replify git
Initialized REPL for [git]
git> init
Initialized empty Git repository in /ebs1/html/test/.git/

git> remote add origin https://your-url/repo.git                

git> checkout -b new-branch
Switched to a new branch 'new-branch'

git> push   
#!/bin/sh
kazinator 1 day ago [-]
Here is my version:
#!/bin/bash
printf "REPL for %s\n" "$@"
notblank()
{
[ $# -gt 0 ]
}
while true ; do
printf "%s> " "$@"
read -r || break;
notblank $REPLY || continue;
eval command \"\$@\" "$REPLY"
done
We keep the original parameters and expand them with "$@". There is a Bash feature that read with no args reads the line into the REPLY variable. We want that to be subject to splitting.
If $REPLY expands to nothing, including multiple whitespace, then we just want to print the prompt again: not quit and not run the command with no additional arguments.
The eval trick allows $REPLY to undergo expansion and splitting, so that shell syntax can freely be used in the REPL.
Test:
$ ~/test/replify/replify.sh git
REPL for git
git> rev-parse HEAD
7ac594319e417266764a6bc041b74807f2fe13bd
git> branch -r
origin/HEAD -> origin/master
origin/master
origin/origin/master
git> checkout "$TERM $TERM"
error: pathspec 'xterm xterm' did not match any file(s) known to git.
git> checkout $TERM
error: pathspec 'xterm' did not match any file(s) known to git.
Cute, but not terribly useful without history recall and related features. This wants to be a feature of Bash. The regular Bash repl should have a prefix variable so it can appear to be in a sub-mode for a particular command.
Submit a patch for Bash to do this, and maybe you have something. Bash has a hook feature for command execution, IIRC, so this may be somehow doable without modifying Bash.
https://news.ycombinator.com/item?id=12322035

See mchav/With for a similar tool that has more features.

@dapithor
Copy link
Author

Use https://github.com/hanslub42/rlwrap and then rlwrap replify ...

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