Wednesday, February 7, 2024

[SOLVED] Type a text on shell prompt

Issue

Is there any way in the shell script by which I can set the input line programmatically? Consider the following scenario.

Let's say I make a script to create a git branch, and right after it is done making a branch, I don't want to switch to new branch programmatically, but just give user the command displayed on the prompt, so user don't have to type the command to switch to new branch but only just press enter key if he wants to run the displayed command.

read -p "Enter your branch name: " N
git branch $N
render-text-on-prompt "git checkout $N"

Execution:

$ ./mkbranch
$ Enter your branch name: change-93
$ git checkout change-93 _

Solution

bash doesn't have a way to "preload" the next input buffer (unlike zsh, in which you can simply use print -z "git checkout $N"). You would need to have mkbranch handle the input (and subsequently execute the entered command) itself.

read -p "Enter your branch name: " N
git branch "$N"
read -e -i "git checkout $N" cmd
eval "$cmd"

-e informs read to use the Readline library for entering the line of text; the -i option preloads the input buffer. (Without the -e the -i doesn't do anything.)

Note that read -e does not itself know anything about bash syntax, so there are no implicit line continuations; this makes it distinctly different from the ordinary bash prompt.

An alternative would be to simply ask the user if they would like to checkout the newly created branch:

read -p "Enter your branch name: " N
git branch "$N"
read -e -i Y -p "Checkout branch $N? (Y/n)"
[[ $REPLY == Y ]] && git checkout "$N"

Hitting enter accepts the pre-loaded Y to trigger the hard-coded `checkout command; any other command skips it. Either way, the script ends and returns to the regular command prompt.



Answered By - chepner
Answer Checked By - Robin (WPSolving Admin)