Clear a terminal screen for real [closed] - linux

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 1 year ago.
Improve this question
Using the clear command on the terminal only fools the user into thinking the screen has been cleared...you can still see output from the previous commands when you scroll using the mouse. This makes life difficult when you are drowning in a tsunami of text.
Various solutions (escape code etc.) which can be found on the Internet are only variations of what the clear command already does.
So how do you clear the contents of a terminal in Linux for real?

Use the following command to do a clear screen instead of merely adding new lines ...
printf "\033c"
yes that's a 'printf' on the bash prompt.
You will probably want to define an alias though...
alias cls='printf "\033c"'
Explanation
\033 == \x1B == 27 == ESC
So this becomes <ESC>c which is the VT100 escape code for resetting the terminal. Here is some more information on terminal escape codes.
Edit
Here are a few other ways of doing it...
printf "\ec" #\e is ESC in bash
echo -en "\ec" #thanks #Jonathon Reinhart.
# -e Enable interpretation of of backslash escapes
# -n Do not output a new line
KDE
The above does not work on the KDE console (called Konsole) but there is hope! Use the following sequence of commands to clear the screen and the scroll-back buffer...
clear && echo -en "\e[3J"
Or perhaps use the following alias on KDE...
alias cls='clear && echo -en "\e[3J"'
I got the scroll-back clearing command from here.

Try reset. It clears up the terminal screen but the previous commands can be accessed through arrow or whichever key binding you have.

tput reset
That will do the trick!

None of the answers I read worked in PuTTY, so I found a comment on this article:
In the settings for your connection, under "Window->Behavior" you'll find a setting "System Menu Appears on ALT alone". Then CTRL + L, ALT, l (that's a lower case L) will scroll the screen and then clear the scrollback buffer.
(relevant to the OP because I am connecting to an Ubuntu server, but also apparently relevant no matter what your server is running.)

Clean the visible screen
clear
Clean screen and clear buffer
clear && clear
Clean and 1-sec delay
reset
Clean without 1-sec delay
tput reset

My favorite human friendly command for this is:
reset
Tested on xterm and VT100. It also helps after an abnormal program termination.
Keeps the command buffer, so up-arrow will cycle through previous commands.

I know the solution employing printing of new lines isn't much supported, but if all else fails, why not? Especially where one is operating in an environment where someone else is likely to be able to see the screen, yet not able to keylog. One potential solution then, is the following alias:
alias c="printf '\r\n%.0s' {1..50}"
Then, to "clear" away the current contents of the screen (or rather, hide them), just type c+Enter at the terminal.

The following link will explain how to make that alias permanent so you don't have to keep typing it in.
https://askubuntu.com/questions/17536/how-do-i-create-a-permanent-bash-alias
These are the steps detailed at that link.
vim ~/.bashrc or gedit ~/.bashrc or what ever text editor you like
put alias cls='printf "\033c"' at the bottom of the file
save and exit
. ~/.bashrc (and yes there should be a space between . and ~)
now check to see if everything worked!
I take no credit for this information just passing it along.

Just to add that tmux scroll buffer does not clear with clear, reset or printf. You need to :clear-history. See link.

With KDE and Ubuntu 12.04 LTS and the "Konsole" terminal, none of the posted answers work. However, pressing default keyboard shortcut CTRL+Shift+X does work! Source:
https://bugs.kde.org/show_bug.cgi?id=288913

echo -e "\e[3J"
This works in Linux Machines

Compile this app.
#include <iostream>
#include <cstring>
int main()
{
char str[1000];
memset(str, '\n', 999);
str[999] = 0;
std::cout << str << std::endl;
return 0;
}

Related

I cant find the files I save in vim [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 5 years ago.
Improve this question
I am trying to learn code using a vim editor as I hear I can get superior long term benefits when I start making long codes and documents. I am a pretty big fan of keyboard shortcuts so I do not mind taking the long road to superior editing abilities. Any way the Linux book I am reading has recommended it and even has many exercises that require typing and saving in vim. The problem is that I cannot find the files I save in vim. I enter the escape mode hit the colon key and use the w option. The vim tells me that the file is saved but when later try to find it in my Linux directory I can find nothing. I have tried using the type, file, find, and locate commands as well as whereis even though this is for commands. Thank you for help in advance.
There is no such thing as escape mode. Most likely you are referring to normal mode. The easiest way to enter normal mode is by hitting the escape key, Esc. Once in normal mode you can save the contents of the current buffer into the file by typing :w. Alternatively you can specify a new file name with :w filename. Then you can quit vim with :q. These steps can be combined by typing :wq.
You mention that Vim tells you the file has been saved but you cannot find the file. In this case type Ctrl-g after saving the file, the file name relative to the current directory should be displayed.
Your "Linux book" almost certainly tells you to do something like:
$ vim filename
with filename being an existing file or a non-existing file. In both cases, doing :w<CR> in Vim, will write filename…
in the working directory if filename is just a file name, without anything "path-like":
$ cd /tmp
$ vim foo.txt
(do your thing)
:wq
$ echo $PWD/$_
/tmp/foo.txt
at the given location relative to the working directory if filename is a relative path:
$ cd ~/Documents
$ vim exercices/foo.txt
(do your thing)
:wq
$ echo $PWD/$_
/home/rubberbandface/Documents/exercices/foo.txt
at the given location if filename is an absolute path:
$ vim ~/Documents/exercices/foo.txt
(do your thing)
:wq
$ echo $_
/home/rubberbandface/Documents/exercices/foo.txt
That said, you shouldn't learn Linux, Vim, and programming at the same time.

how to execute a function in i3 config? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed 4 years ago.
Improve this question
I want to rename a workspace but retain the workspace number by default, in i3 user guide, I find the following script to do so.
bindsym $mod+r exec i3-input -F 'rename workspace to "%s"' -P 'New name: '
But the problem is that it doesn't keep workspace number by default, so I have to remember to type the workspace number.
I've found a way to get the number of the focused workspace number with following command, but I don't know how to concat the number to with the input name together in i3 config.
i3-msg -t get_workspaces | jq '.[] | select(.focused == true) | .num'
So, I'm wondering whether in i3 config file, I can execute some kind of function to concat the workspace number with user input to achieve my purpose?
I don't think you can. But, you can always do whatever you want if you create a script and call it with exec in your i3-config. So, for example:
~/bin/i3-rename-workspace (or wherever is convenient for you):
N=$(i3-msg -t get_workspaces | jq '.[] | select(.focused == true).num')
i3-input -F "rename workspace to \"$N: %s\"" -P 'New name: '
Somewhere in your i3-config:
bindsym $mod+r exec i3-rename-workspace
Remember to provide the full path to your script, or put it somewhere in i3's $PATH.
You can execute a function from the i3 config, it gets a bit hairy but it works out quite nicely. The key things to remember are any commands with a , or ; need quoted (i.e. every function you can possibly write as it is a required part of the syntax), and if you have additional quotes of the same type inside the command passed to exec you need to escape them with \\ per the i3 documentation.
Personally I wanted a simple shutdown menu without having to create a separate script to maintain and drag around outside my i3 config, I used an inline function definition and call. This is very similar to the recommended way to run external commands in git aliases (and is where I had the idea that it would work).
bindsym $mod+Shift+q exec "bash -c 'f () { res=$(rofi -dmenu < <(echo -en \\"logout\nrestart\nshutdown\\")); case $res in logout) i3-msg exit;; restart) sudo shutdown -r +2;; shutdown) sudo shutdown -P +2;; esac; }; f;'"
This is a bit dense to unpack, but I define the temporary function f () {...}; f;' and call it after. Inside the function I'm feeding in the options to the menu using process substitution and input redirection to capture the selection to a variable res=$(rofi -dmenu < <(echo -en \\"logout\nrestart\nshutdown\\")) and note the extra \\ to escape the inner double quotes.
Finally I'm evaluating the option the user selected via case and choosing an action based on that option, with a 2 minute timeout on the restart and shutdown commands so I can abort if somehow I hit the hard to accidentally hit modifiers required to trigger the menu AND select an item rather than just pressing Esc to exit the menu.
After writing this up and realizing how easy it might be to logout and loose all my current windows/layouts, I'm going to add a "no-op" option that appears first in the list and is evaluated last in the case statement that maybe will echo something funny via cowsay or notify-send.

Save and restore terminal content

I am writing automation scripts (perl/bash). Many of them benefit from some basic terminal GUI. I figured I'd use standard ANSI sequences for basic drawing. Before drawing in terminal I do clear but doing that I lose some terminal command history. I want to be able to restore terminal command history when my program exists. Many terminal programs (e.g. less, man, vim, htop, nmon, whiptail, dialog etc) do exactly that. All of them restore terminal window bringing the user back to where he was prior to calling the program with all the history of commands previously executed.
To be honest I don't even know where to start searching. Is it a command from curses library? Is it an ANSI escape sequence? Should I mess with tty? I am stuck and any pointers would be really helpful.
EDIT: I'd like to clarify that I am not really asking "how to use the alternative screen". I am looking for a way to preserve terminal command history. One possible answer to my question could be "use alternative screen". The question "what is alternative screen and how to use it" is a different question which in turn already has answers posted elsewhere. Thanks :)
You should use the alternate screen terminal capability. See
Using the "alternate screen" in a bash script
An answer to "how to use the alternate screen":
This example should illustrate:
#!/bin/sh
: <<desc
Shows the top of /etc/passwd on the terminal for 1 second
and then restores the terminal to exactly how it was
desc
tput smcup #save previous state
head -n$(tput lines) /etc/passwd #get a screenful of lines
sleep 1
tput rmcup #restore previous state
This'll only work on a terminal has the smcup and rmcup capabilities (e.g., not on Linux console (=a virtual console)).
Terminal capabilities can be inspected with infocmp.
On a terminal that doesn't support it, my tput smcup simply return an exit status of 1 without outputting the escape sequence.
Note:
If you intend to redirect the output, you might want to write the escape sequences directly to /dev/tty so as to not dirty your stdout with them:
exec 3>&1 #save old stdout
exec 1>/dev/tty #write directly to terminal by default
#...
cat /etc/passwd >&3 #write actual intended output to the original stdout
#...

In a bash script, print command (as a suggestion) on the prompt after the script exit

I'd like to write a shell script that can suggest a command by printing it after the command line prompt.
Then, after the scrip exit, the user would only have to press the [enter] key to run this suggested command.
Given that I'm new to bash, I don't even know if it is possible to do this. I thought about using a copy-past command, moving the cursor, use the $PS1 variable, without finding a suitable way..
Does anyone have any clues on how such feature could be implemented ?
Following the suggestion of Landen in the comments (thanks a lot!), I've been able to produce a workaround for my problem.
This workaround needs the xautomation package (xte command, emulating key pressed), is not very robust, and may depends on the keyboard layout handling of xautomation, and system shortcuts. For example, I had to change the shortcut for the unity HUD.
But given that my command is very fast, and that is is mostly for personal use, this solution fits perfeclty my needs:
COMMAND_PASSED='sudo apt-get update'
# Displays the content of $COMMAND_PASSED on the next prompt
xte "str $COMMAND_PASSED"
sleep 0.1
tput cub ${#COMMAND_PASSED}
sleep 0.1 and tput cub ${#COMMAND_PASSED} commands are needed to prevent the keys from being also displayed before the command prompt.
sleep 0.1 makes the whole command to be printed before the prompt.
tput cub ${#COMMAND_PASSED} move the cursor backward to make sure that all unnecessary prints are erased.
Thanks everyone!

Redraw screen in terminal

How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen?
Depending on the terminal you send control seuqences. Common sequences are for example esc[;H to send the cursor to a specific position (e.g. on Ansi, Xterm, Linux, VT100). However, this will vary with the type or terminal the user has ... curses (in conjunction with the terminfo files) will wrap that information for you.
Many applications make use of the curses library, or some language binding to it.
For rewriting on a single line, such as updating progress information, the special character "carriage return", often specified by the escape sequence "\r", can return the cursor to the start of the current line allowing subsequent output to overwrite what was previously written there.
try this shellscript
#!/bin/bash
i=1
while [ true ]
do
echo -e -n "\r $i"
i=$((i+1))
done
the -n options prevents the newline ... and the \r does the carriage return ... you write again and again into the same line - no scroling or what so ever
If you terminate a line sent to the terminal with a carriage return ('\r') instead of a linefeed ('\n'), it will move the cursor to the beginning of the current line, allowing the program to print more text over top of what it printed before. I use this occasionally for progress messages for long tasks.
If you ever need to do more terminal editing than that, use ncurses or a variant thereof.
There are characters that can be sent to the terminal that move the cursor back. Then text can be overwritten.
There is a list here. Note the "move cursor something" lines.
NCurses is a cross-platform library that lets you draw user interfaces on smart terminals.
Corporal Touchy has answered how this is done at the lowest level. For easier development the curses library gives a higher level of control than simply sending characters to the terminal.
To build on #Corporal Touchy's answer, there are libraries available that will handle some of this functionality for you such as curses/ncurses
I agree with danio, ncurses is the way to go. Here's a good tutorial:
http://tldp.org/HOWTO/NCURSES-Programming-HOWTO/

Resources