I am using the following code to take input from user interactively,
thus allowing the user to make changes to the input without deleting the entire line.
#! /bin/bash
while :
do
echo -n "prompt# "
read -e input
done
Problem:
It also allows me to delete the "prompt#", which I don't want to happen.
I don't want the "prompt# " to be deleted by the user in any case.
I've tried using various options in read command but can't figure it out.
How can I achieve this?
Edit:
The sequence of events that led to the problem:
1. I ran the above script and entered "hello".
2. Then I moved my cursor to 'e' in "hello" and "pressed and held" backspace for some time which resulted in the deletion of the "prompt# "
3. If you don't type any characters it works fine and the prompt is not deleted but if you enter even a white space or any character and then press the backspace then it messes the prompt.
Take a look at the snapshot below.
Snapshot:
From 4ae1e1's comment:
You should use read's builtin prompt support, or you're on your own.
read -p 'prompt# ' -e input
Related
This question already has answers here:
Using the "alternate screen" in a bash script
(3 answers)
Closed 9 months ago.
I try to make a simple bash script that runs multiple tools, like dehader, cppcheck and a bunch of custom tools, and for readability, it cleans the terminal between each tool, and wait for the user to press the enter key before running the next tool.
clear
rm *.o
echo "removed object files"
rm __pycache__
echo "removed python cache files"
echo "everything cleaned, press enter to continue"
read a
clear
deheader
echo "deheader done, press enter to continue"
read a
clear
cppcheck
echo "cpp check done, press enter to exit"
read a
clear
Simple reproduction of what my script does
But I don't like this solution, because I want this script to execute in another screen (I don't know how to call it exactly), just like less does. This way, I could keep my terminal just like it was before the script call. Even if they aren't close to the less behavior, any suggestions that could help me are welcome.
I searched online what I could do to reproduce this behavior, but didn't find anything. I'm starting to doubt that's even possible.
Note: I don't want the 'scrolling' less behavior. I mean, there's no problem if I have to use it, but I don't particulary want it.
I think you want to run a new Terminal window and get back the prompt in your current Terminal window. If so, start a new Terminal that runs a command with lots of output and pipe it through less:
xterm -e "ls -lR / | less" &
The & runs the command in the background and gets you your prompt back in the current Terminal window.
Thanks to the comments, I figured it out.
From what I can understand, there are two ways to do it with the "cursor addressing mode":
By using tput smcup/rmcup
By entering/exiting the "cursor addressing mode" manually, when priting the escapes sequences related
This mode in terminal-implemented and is not supported by all terminals - and not always in the same way, for example multiple terminals don't reset the cursor position after entering this mode, so don't forget to clear your terminal - but is fortunately supported by a large majority of modern terminal emulators.
smcup/rmcup
Simply use the tput smcup command, and then, restore it using tput rmcup.
Example:
# save, clear screen
tput smcup
clear
# example "application" follows...
read -n1 -p "Press any key to continue..."
# example "application" ends here
# restore
tput rmcup
source
Escape sequence
You can enter this mode using printf \\33\[\?1047h, then leave it using printf \\33\[\?1047l.
Example:
# save, clear screen
printf \\33\[\?1047h
clear
# example "application" follows...
read -n1 -p "Press any key to continue..."
# example "application" ends here
# restore
printf \\33\[\?1047l
more informations
Try to avoid using both methods in the same code, or using one method to enter this mode and another to exit it, as it could lead to unexpected behavior.
Personnaly, I prefer the tcup method as it's more readable and supported by all Unix systems.
Some times that I have a command ready to press enter but that command I have changed it in some way and it's a long command, then I remember that I have to open a text file (e.g. to get some information that I will use in the command). So what most of the times I do, is to cancel that command (Ctrl+C) and then open the text file get the information I need and then retype the command again with the pasted value from the text file. This is not very efficient for me specially if the server doesn't have any kind of GUI and I can't copy the previous command so I don't lose it.
So my question is, Is there any kind of combination keys that I could use to save a command ready to enter so I don't lose it and I don't have to type it all over again?
Thanks!
This is currently not possible out of the box.
The easiest way to do it is probably to
Change the cancel binding to stash the commandline
Add a binding to recall the stashed commandline
It would work something like this:
The function to recall:
function recall_commandline
if set -q stashed_commandline
commandline -r -- $stashed_commandline
end
end
Add to __fish_cancel_commandline (use funced __fish_cancel_commandline. Once you are happy do funcsave __fish_cancel_commandline):
set -g stashed_commandline $cmd
# right before:
commandline ""
Add to fish_user_key_bindings
bind \cr recall_commandline
This will allow you to press Ctrl+r to recall the last cancelled commandline. Expanding it to multiple is non-trivial (since "commandlines" can have multiple lines), as is adding the commandlines to history so that they can be recalled with the normal bindings.
I have the following function to turn comment/uncomment the current statement:
function toggle-comment-cmd-buffer --description 'Comment/Uncomment the current or every line'
set -l cmdlines (commandline -b)
if test "$cmdlines" = ""
return
end
set -l cmdlines (printf '%s\n' '#'$cmdlines | string replace -r '^##' '')
commandline -r $cmdlines
string match -q '#*' $cmdlines[1]; and commandline -f execute
end
I bind it thusly: bind \e\# toggle-comment-cmd-buffer. This way I can quickly comment and put the current statement in my command history in order to do something else. Then I can recall the comment and press [alt-#] again to remove the comment characters and continue modifying the command.
I set this up in my personal fish config because I had gotten used to doing something similar in ksh93.
I'm trying to use vim with -s option to run a script that replaces some lines in a file like this (text.txt):
test1
ab
ac
ae
test2
sd
Script file is like this (script):
:silent %s/test1\zs\_.\+\zetest2/\=substitute(submatch(0), '\n\(\w\)', '\n#\1', 'g')/g
:wq
It comments out lines between test1 and test2. Which is what I want. What I don't want though is output before and after prompt. I run it and get:
user#hostname: ~/vimtest$ vim -s script text.txt
^[[?1;2cuser#hostname: ~/vimtest$ 1;2c
So this ^[[?1;2c is bad news already but 1;2c is in the input as if I already typed it. If I hit enter it gives me a bash error. So I have to remove these symbols each time the script is used. Any ideas?
It seems like vim (or some vim startup script) is trying to figure out what type of terminal you are using. The ^[[?1;2c, with the last few characters left in the input buffer, is almost certainly part of your terminal emulator's response to a DA (Device Attributes) query. You can see this yourself by typing in bash:
printf '\033[c'
or, to see the complete return, pause a bit:
printf '\033[c'; sleep 0.1; echo
The response \033[?1;2c means "I'm a VT100 with Advanced Video Option.", which is what xterm and many other console programs respond. (The Linux console itself responds \033[?6c, which means "I'm a VT102.")
The reason that only 1;2c is left in the console input buffer, by the way, is that the initial escape code \033[? was ignored when it was read. The readline library will ignore it without echoing it, whereas normal console input will echo it and then ignore it; that's why the two shell commands above differ.
I can't reproduce this problem with my vim installation, so I don't really even know where to start looking. But you might try to see if disabling all startup files helps:
vim -u NONE -s script text.txt
If that helps, start disabling installed extensions one by one until you find the one which is causing the problem.
:%s/test1\zs\_.\+\ze\ntest2/\=substitute(submatch(0), '\n', '\n#', 'g')/g
:wq
this is tested here, it changed the input file in required way.
Some changes done based on your command:
add \n after \ze
in substitute() function we can just handle the \n, we don't need to capture the word after the \n
I noticed that you tagged the question with bash, so I thought a shell-solution should be accepted too.
awk '/test1/{p=1;print;next}/test2/{p=0;print;next}{$0=(p?"#":"")$0}7' file
this awk oneliner should do that for you. vim is very powerful editor, I love vim. But if you want to do some automatic transformation, I prefer a script or a proper text processing tool. On a linux box you can always find one. It is easier to test and debug.
Test with your input:
kent$ cat f
test1
ab
ac
ae
test2
sd
kent$ awk '/test1/{p=1;print;next}/test2/{p=0;print;next}{$0=(p?"#":"")$0}7' f
test1
#ab
#ac
#ae
test2
sd
If you want to save the text back to your file, you can :
awk '...' file > tmp.file && mv tmp.file file
I've just started using Terminal (the CLI for Mac OS X).
When I run a command, get some information back, run another command, get more info etc., it is hard (on the eyes) to find a certain point on the screen (e.g. the output for the command before last).
Is there a way of adding a vertical empty space to the end of each output/ after each command is run that has no output?
Each new command that you enter is preceded by a "prompt", and these can be customized (though the exact way to customize depends on the shell). Since you mention Mac OS X I'm assuming you are using the default bash shell, in which case the absolute simplest way to add a blank line is like this: PROMPT_COMMAND=echo. You can run that command to try it out, or add it to a startup file (like .profile in your home folder) to have it done automatically each time.
If you use Bash 4.4 and you want a blank line after your prompt, you could set the PS0 prompt to a newline:
PS0="\n"
Now, this will be inserted every time you run a command:
$ echo "Hello"
Hello
Wondering this too, I've looked at the menu options in Terminal & most of the control characters one can type in and nothing does this on a keystroke. You can however enter an echo command, it alone to leave a single blank line below it before the next prompt. echo \n will add an extra blank line to that, echo \n\n to do 2 extra, ie. 3 blank lines, etc. (you can also do echo;echo;echo getting the same effect)
You can create a shell alias like alias b='echo;echo' (i couldn't seem to get the \n notation to work in a alias), then entering b on a prompt will leave a double-blank line, not bad. Then you gotta figure out how to save aliases in your .profile script.
I tried making an alias for the command ' ' ie. space character, which I though you could type like \ (hmm, stack overflow not formatting this well, that's backslash followed by a space, then return to execute it), but the bash shell doesn't seem to allow an alias with that name. It probably wouldn't allow a function named that either (similar to alias), though I didn't check.
I often use the fish shell, and I found that it does allow a function with that name! Created with function ' '; echo \n; end and indeed it works; at the shell prompt, typing the command \ (again backslash space) leaves a double blank line.
Cool, but.. I tried saving this function using funcsave ' ' (how you save functions in fish, no messing with startup scripts!) and afterwards the function no longer works :^( This is probably a bug in the fish shell. It's in active development right now though, I think I'll report this as a bug since I would kind of like this to work myself.
One could also send Apple a feature request through their bug reporter for an Insert Blank Line menu/keyboard command in Terminal. If someone pays attention to your request it might be implemented in a year maybe.
I wanted to solve exactly the same, and for anyone interested in doing the same, I used what tripleee said in his comment here - I created a .bash_profile (see details here) with the line export PS1="\n\n$ ".
Hopefully that helps someone else too!
I'd like to have a blank line after my bash prompt and before the output on my Mac. It should look like this would:
echo; ls
Can I add a newline to my bash prompt and then go back up one line to wait for user input? Is there something obvious I'm missing?
I know this is old but for someone like me who came across this while googling for it. This is how you do this...
It's actually pretty simple!
Check out this link --> Cursor Movement
Basically to move up N number of lines:
echo -e "\033[<N>A HELLO WORLD\n"
Just change the "< N >" to however many lines you want to go back...
For instance, to move up 5 lines it would be "/033[5A"
To my knowledge this is not possible unless you delve into more low-level stuff like full-screen emulators like curses.
This is a bit of a stab in the dark, but you may be able to use VT102 terminal codes to control the cursor without having to use Curses. The relevant VT102 commands that you'd be interested in all consist of sending ESC, then [, then the specific command parameters.
For instance, to move the cursor up one line, one needs to output:
ESC [ 1 A
0x1B 0x5B 0x31 0x41
Be warned that the VT102 documentation generally uses octal, so keep an ascii table handy if you're using hex.
All of this advice is given without having tested it -- I don't know if VT102 commands can be embedded into your bash prompt, but I thought it might be worth a shot.
Edit: Yeah -- looks like a lot of people use VT102 formatting codes in their bash prompts. To translate my above example into something Bash would recognize, putting:
\e[1A
into your prompt should move the cursor up one line.
This is very possible. If your bash has C-v set as the readline quoted-insert command, you can simply add the following to your ~/.inputrc:
RETURN: "\C-e\C-v\n\C-v\n\n"
This wil make bash (readline, actually) insert two verbatim newlines before a regular interpreted newline. By default, only one is inserted, which is what causes output to start on the line after the prompt.
You can test if C-v is set to quoted-insert by typing it in bash (that's Ctrl+V) followed by e.g. an up arrow. This should print ^[[A or something similar. If it doesn't, you can bind it in ~/.inputrc too:
C-v: quoted-insert
RETURN: "\C-e\C-v\n\C-v\n\n"
~/.inputrc can be created if it doesn't exist. The changes will not take effect in running bashes unless you issue a readline re-read-init-file command (by default on C-x C-r). Be careful though. If you do something wrong, enter will no longer issue commands, and fixing your mistake could prove to be difficult. If you should do something wrong, C-o will by default also accept the line.
Adding a newline followed by moving the cursor back to the regular prompt (like you described) is possible, but will not have the effect you intend. The newline you inserted would simply be overwritten by the application output, since you moved the cursor back in front of it.
This works:
trap echo DEBUG
It doesn't add an extra newline if you hit return at an empty prompt.
The command above will cause a newline to be output for every member of a pipeline or multi-command line such as:
$ echo foo; echo bar
\n
foo
\n
bar
To prevent that so that only one extra newline is output before all command output:
PROMPT_COMMAND='_nl=true'; trap -- '$_nl && [[ $BASH_COMMAND != $PROMPT_COMMAND ]] && echo; _nl=false' DEBUG
The DEBUG trap is performed before each command so before the first command it checks to see if the flag is true and, if so, outputs a newline. Then it sets the flag to false so each command afterwards on the line doesn't trigger an extra newline.
The contents of $PROMPT_COMMAND are executed before the prompt is output so the flag is set to true - ready for the next cycle.
Because pressing enter on an empty command line still triggers the execution of the contents of $PROMPT_COMMAND the test in the trap also checks for those contents as the current command and doesn't perform the echo if they match.
I believe (but haven't tried) if you put '\n\b' in the prompt string it would do that.
In general, if you want to find out the codes to do anything a terminal can do, read the terminfo man page.
In this case, the cursor up one line code can be determined by:
tput cuu1
If you redirect the tput output to a file, you can see what control characters are used.
Bash also supports the PROMPT_COMMAND variable, allowing you to run arbitrary commands before each prompt is issued.