History of commands in the shell

The best command to review most recent commands:

fc -lr

 The above command lists the latest commands in reverse order. It doesn’t list many. To see the entire list, type:

fc -l 1 | less

Simple fc without any arguments picks the latest command in the history, opens it up in your preset command-line editor, and then launches it when the editor closes. There is no stopping the launching, as far as I know, except by emptying the editor and closing it.

To launch an editor according to my liking and with arguments I don’t ordinarily use in that editor, I use:

fc -e "nano -k -U"

Additionally, there’s a way to re-launch commands by means of fc. For this, do first fc -lr to get some commands with their respective history numbers and memorise the number you want to re-launch. Then:

fc -ls #

where # is the number. This re-launches without editor (the argument -s does that). More info:

man fc

Inform thyself of the commands in your computer

man + cmd usually gives the most in-depth answer when seeking information about a command. Most Linux commands have man pages. Some don’t.

In case of missing man pages, the given command may provide information about itself by one of the following:

cmd --help

cmd -help

cmd -h

Substitute cmd for the command you want to know about.

Additionally, there are special commands on Linux whose function is to provide information about other commands. Some of them are:

type cmd

whatis cmd

whereis cmd

Find out the time in other time zones

TZ='America/Chicago' date --date='TZ="Europe/Berlin" 2100'

This command will output the answer to the question: When it’s 2100 (9:00 p.m.) in Berlin, then what’s the time in Chicago?

To find the timezones you need, use tzselect.

Make Aspell actually work

Aspell is a command-line spellchecker, useful for Nano and Mutt for example. The only problem is get it actually to work.

System Locale versus Spelling Dictionary

Aspell works out of the box if your system locale is English and you want to spell check only the same language. This is not mostly the case. My system locale is different, but I want to spell check English.

Command-Line Options versus Configuration File

Aspell’s behaviour can be modified by adding command line options, but this is useless, because normally Aspell is invoked from another program, such as Nano or Mutt. Aspell’s behaviour can be modified also by tweaking a config file, which would be useful, if the instructions on how to do it were not utterly confusing.

The config files mentioned on man aspell are not in the indicated locations, not in my system at least. The way to get access to the content of configuration options is to do

aspell dump config > .aspell.conf

This creates the file .aspell.conf whose settings Aspell will follow, when set correctly. Initially the content is entirely commented out and this is a good thing, because nothing in there is usable. You can try uncommenting some lines, but you will see that these are not workable settings when you invoke Aspell.

Setting a Spellcheck Dictionary

If your system locale is other than the spellcheck language that you need (which is the case for pretty much everybody outside the English-speaking world), you will need to first install an English dictionary in addition to Aspell itself. The name of the package to install may be aspell-en or aspell-uk. Both are English, but the latter is British.

After the necessary dictionaries have been installed, open the .aspell.conf file. Add the lines,

  lang en  master en 

This makes Aspell workable for a start. Other settings may be useful too, but they are beyond my scope.

Some Tmux Routines

Tmux is a terminal multiplexer. A terminal multiplexer enables to run multiple clients inside a single terminal in a tiling manner. Another famous terminal multiplexer is GNU ‘screen’, but Tmux is prettier and easier to configure in my opinion. Here’s a comparison between them http://dominik.honnef.co/posts/2010/10/why_you_should_try_tmux_instead_of_screen/

Introductory Keybinds in Tmux

So, what does Tmux do? After installation, open up a terminal emulator and type tmux. You will have a new emulator screen with a cute status bar. Open an app there or leave a process running.

Next, type Ctrl+b. This is the prefix for all the commands given to Tmux rather than to the app or process (called “client”) you are running inside of it. The prefix done, press (i.e. prefix+c). A next screen opens up. The status bar will show you how many screens (called “windows”) are opened and you can determine in which one your current focus is.

To switch between windows, press prefix+n (for next window) or prefix+p (for previous window). By default, these keys should cycle through all, i.e. prefix+n should take you to the first window, when you are currently in the last window.

Prefix+” will split the current window into two tiles (called “panes”) horizontally. Prefix+% will split it further vertically.

Prefix+o will move focus to another pane in the current window. Prefix+space will switch to a different layout. There are several layouts, so try prefix+space multiple times to see them all.

Prefix+z will zoom the focused pane over the entire window. Prefix+o (i.e. move focus on another pane in the same window) shrinks the zoomed pane.

Resizing the panes should be possible by dragging the border of the pane with mouse. The rest of the keyboard shortcuts are under prefix+?.

Copying in Tmux

There are enough basic intros to Tmux on the internet already, so I’ll better focus on the awesome copy-paste function, which is otherwise rather difficult to achieve in terminals.

There are two modes for copy-paste, Vim and Emacs. The more likely default is Emacs and I like it better, so here’s a list of its basic routines.

Prefix+[ or Prefix+PageUp enters the copy mode. An indicator lights up in the upper right corner.

Use the arrow keys (without prefix) to get to the point you want and Ctrl+space (without prefix) to begin selecting. Use arrow keys again to draw out the selection and Alt+w (without prefix) to copy the selection.

Upon copying, the copy mode indicator vanishes from the upper right corner, i.e. the copy mode terminates at Alt+w. If you want to exit the copy mode any time when it’s active, press Escape or Ctrl+c.

To paste, move with arrow keys (and switch the panes and windows if necessary) to the spot where you want to paste the copied content (called “buffer”). On the spot, press prefix+] to paste or prefix+= to see the buffer and then Enter to paste.

Copying and pasting in Tmux is rather important, so let’s try again. There are some nice pages in Tmux, such as the internal help page, which are in copy mode even without entering the copy mode, and this is good for exercise.

A note: Tmux copy-paste buffer is available only inside Tmux, not in other apps and not on the clipboard.

A Small Exercise of Copying and Pasting in Tmux
  1. In Tmux, open up a new clean window; prefix+c
  2. Open up the list of keybinds; prefix+?
  3. Move to the line you want with the arrow keys
  4. Ctrl+a goes to the beginning of the line
  5. Ctrl+space begins selection
  6. Ctrl+e goes to the end of the line; the line becomes selected
  7. Alt+w copies the line and closes the list of keybinds
  8. Prefix+? to open the list of keybinds again
  9. Now move to a different line to select it
  10. Select and copy the line the way you just did a moment earlier; the list should close by the end of this operation
  11. Now, facing the console, press prefix+= which should bring up at least two buffers to select from, if you did everything right
  12. Press Enter to paste the selected buffer
  13. Repeat until you have mastered the procedure

Attach and Detach Tmux Sessions

Attaching and detaching sessions is an advanced feature, but worth some practising too. First let’s go over some terminology again.

Clients (apps or processes) run inside panes and there can be multiple panes in a window (a single screen view of the terminal emulator or console). All these windows make up a session.

The new session starts as soon as Tmux is started. Prefix+s provides a list of running sessions and an opportunity to switch between them. Selecting a session this way is called attach.

Prefix+d detaches the session. This means that even when you close the terminal emulator where you had Tmux running, all the processes in the session remain active as long as the user session in the computer remains active (i.e. don’t log out, don’t shut down the computer).

To test the attach/detach feature, press prefix+d to detach from the running session in the terminal emulator. Close the terminal emulator and open up the console (tty, normally Ctrl+Alt+F2 through F6 in Linux).

In console, log in as the same user and type tmux. In Tmux, press prefix+s. You should see at least two sessions running. That’s the idea of attaching and detaching.

Configuring Tmux

There should be a configuration file located at /etc/tmux.conf, but if not, create an empty file at ~/.tmux.conf. As long as it’s empty, Tmux uses its defaults. If there’s something in ~/.tmux.conf, Tmux uses that. My ~/.tmux.conf looks as follows.

set -g default-terminal "screen-256color"  ##useful info on the status bar (if I use it): temperature, load, battery, and clock  set -g status off set -g status-position top set -g status-right "[#[fg=red,bright] #(cat /sys/class/hwmon/hwmon0/temp1_input | colrm 3) °C#[default] ][#[fg=cyan,bright] #(cat /proc/loadavg | colrm 5) #[default]]#[fg=green]#[bg=black] #(cat /sys/class/power_supply/BAT0/capacity)% #(cat /sys/class/power_supply/BAT0/status) #[default]#[fg=yellow,bright] %a %R #[default]" set -g display-time 3000 set -g mouse-resize-pane on set -g visual-bell on set -g bell-action none set -g visual-activity on set -g lock-after-time 3000  ##useful titles: window number, process name, and its tmux status set -g set-titles on set -g set-titles-string "tmux.#I.#W.#F" setw -g aggressive-resize on  ##unbind the default keys so they can be reassigned  unbind-key - unbind-key s unbind-key p unbind-key f unbind-key q  ##to see the status bar when needed bind-key b set-option status  ##get the focused pane out of the way into a new background window bind-key - break-pane -d  ##expand the sessions list to select a window interactively bind-key s choose-tree -suw  ##a useful list of all panes to see something to fetch ##the last item with % included is most useful for fetching bind-key p list-panes -asF '#I.#P.#W.#D'  ##fetch a background pane into the current window bind-key j command-prompt "join-pane -ds '%%'"  ##reload the configuration file bind-key f source-file ~/.tmux.conf \; display-message "configged!"  ##monitor activity in the focused window bind-key a set-window-option monitor-activity \; display-message "monitoring this window"  ##kill all sessions except the named one bind-key q command-prompt "kill-session -at '%%'" 

Byobu: More than Tmux

If Tmux seems hard, try Byobu that is gleefully configured out of the box and pretty much explains itself as you use it. The keybinds are totally different from Tmux though, no relation at all.

Some Top Routines

Top or ‘top’ is a process viewer-and-manager for Linux. Another one is Htop or ‘htop’ that comes with more one-key shortcuts and a saner default display (colours that are more likely to be visible). However, Htop’s single-hit keybinds for e.g. killing the currently selected process easily make the user vulnerable to fatal accidents. Also, Htop is not pre-installed too often, so it’s a good idea to know some Top.

top

It’s not too difficult.

  • Open up a terminal emulator
  • Type top and hit Enter
  • At this point, I normally want to change the colours. Shift+z takes to the page where to select colour schemes, a cycles between the schemes, q returns to the processes page.
  • The processes are ordered whichever way, but Shift+p orders them by CPU usage.
  • If the refresh interval is too fast, d lets you change it.
  • Want to kill a process? Shift+l lets you filter up a process and k begins the step-by-step procedure of killing it.
  • Shift+w saves the state, so that next time you open Top, it shows the same colours and lists the processes by CPU.
  • A helpful list with more shortcuts and keybinds is found under h.
  • q quits.

Two simple ways for dual panes in Thunar

Thunar is my preferred file manager, but a lack of dual panes (F3 in e.g. PcmanFM and Nemo) for easy drag-and-drop is sorely missing. There’s an installable patch somewhere on the internet, but patches are too geeky to install. Here’s how to survive without patches, while not missing out on the functionality of dual panes in Thunar.

Method number 1: Open Two Windows

That’s right! Two windows provide the same functionality as dual panes, so get accustomed to opening up two windows of Thunar, arrange them neatly, and then drag-and-drop etc. as you wish. Xfce, the default desktop environment which includes Thunar, has some auto-tiling functionality these days, which comes in conveniently handy for arranging windows.

Two windows Thunar

Depending on the way you arrange the windows, you may want to get rid of the sidebar in one of the windows. The keyboard shortcuts Ctrl+b and F9 do that in Thunar.

Method number 2: Midnight Commander

Method number 2 requires two things: 1. Midnight Commander and 2. Creating a custom action in Thunar. If you like Midnight Commander, a command-line file manager with dual panes, and you have it installed, this method is for you. This way, in addition to dual panes, you will get also the flexibility and speed of command line.

Custom action for Midnight Commander in Thunar menu

An earlier blog post described how to set up custom actions in Thunar. In my case, the code that worked for this custom action:

exo-open --working-directory %f --launch TerminalEmulator mc -b

In addition to this code, remember to unset everything in Appearance Conditions and leave only Folders – the same appearance conditions as for Terminal custom action.

This will launch Midnight Commander with -b option so as to get rid of its default colors. If you have a transparent terminal emulator, the additional advantage with this option is that you will get background visibility to Thunar. This is properly triple panes, even better than dual panes.

Midnight Commander launched from Thunar

Max Windows Openbox Hack

In an earlier post I introduced tiling desktops a.k.a tiling window managers whose notable feature is to make maximum use of screen estate. This post is about how to make Openbox always open maximised windows.

Just in case, make a backup of Openbox main configuration file .config/openbox/rc.xml. This is the file that needs some editing.

Open up the rc.xml and find the section <applications>. This must be a major section, not a command concerning a specific application.

In that section, insert:

  <application class="*">           <decor>no</decor>            <maximized>yes</maximized> </application>     <application type="dialog">         <decor>yes</decor>        <maximized>no</maximized> </application> 

The first codebit tells Openbox to maximise all windows and lose their decorations. If you want to keep the decorations, don’t use the <decor> tags.

The second codebit (beginning with the line containing “dialog”) tells Openbox to exempt dialogs from maximisation. This works for applications that have their dialogs and prompts properly codified as such. Not all of them are properly done. 

Additionally, you may want to exempt some specific apps from getting maximised. For example the messenger: 

  <application class="Pidgin">         <decor>yes</decor>        <maximized>no</maximized> </application> 

Note the class property in application tag. Mostly the ordinary application name fits into that property. Another possibility is to use the name property, which should be the text on the titlebar.

To assign class and name properties rightly, use the command-line tool obxprop which probably comes with every Openbox. It’s used as follows:

  1. In terminal, type obxprop and Enter (it as if stalls, let it be)
  2. Switch to the window whose class/name info you want – by keyboard shortcut, not with mouse
  3. Click on the window
  4. Turn back to the terminal and find the relevant class/name info to put into rc.xml

All necessary changes done, save rc.xml, run openbox --reconfigure and see the effect of the changes to your windowing.

Tiling versus Windowing

In more established terminology, stacking window managers are distinguished from tiling window managers, but I prefer to think of them as windowing desktops versus tiling desktops. The first type is vastly more widespread. Windowing is the main idea behind all Windows releases (it got slightly fuzzier with the unpopular release 8, but was restored in 8.1 and stays so in version 10). Tiling involves specialised and geeky desktops, but is not really more complicated than windowing, particularly if the user is keyboard-centric, as distinguished from mouse-driven.

The main characteristic that sticks out in windowing desktops (‘stacking window managers’ in more established terminology) is that application windows can be maximised, minimised (‘iconified’ in Linux terminology), and stacked partially above each other. Thus there are layers of placement on the desktop (‘top’ and ‘lowered’) and a mouse-click or cycling keybind (Alt+Tab) will raise a lowered window above others, i.e. to the top layer.

In contrast, a tiling desktop presents application frames (‘windows’) in neatly ordered tiles in a single layer. There’s no lowering or raising, there’s just shifting focus from a tile to another by keybind or mouse. Normally there are no breaks in between the frames, so the space is put to maximum use automatically. Due to a single layer and tight positioning, any resizing and repositioning of a tile affects all other tiles. It is usually inconvenient with a mouse and cannot be done without consideration to the whole layout of the workspace. i3wm tiling

Some notes on the tiling desktop in the image. You may want to fullscreen the video, but this would naturally leave the rest of the tiles behind – which is similar to any windowing desktop. Alternatively, you may want to maximise the text editor window and resize the video smaller in a corner, for example when transcribing from the video, to give maximum space for writing and minimal necessary space to the video. In normal tiling mode, the video tile would always take up a column or row equal to its width or height, but on some tiling desktops there’s a specific ‘floating’ mode that can be assigned to a specific tile. However, the floating tile would always be on top of the rest of the layout – there’s no concept of layers, i.e. raising or lowering.

There’s also no concept of minimising or iconifying in a tiling desktop. You cannot add icons to the desktop to click and you cannot minimise all frames to view the desktop. To view the desktop (the background image or conky or what you may have there), you will need to open up a new fresh desktop space.

On the other hand, creating a maximally useful layout with two apps side by side is extremely easy in a tiling desktop. The classic dual-pane view of two apps side by side (as in comparing documents) is what normally happens in a tiling desktop all by itself when you open up the first app (it comes up maximised) and then the second (the first one resizes to take up half of the workspace and the second one takes up the other half). Very convenient.

When you want more apps open than the workspace can fit, there are easy default keybinds to send the focused tile to another workspace. If you cannot do without the experience of raising and lowering, you absolutely need multiple workspaces in a tiling desktop. Some tiling desktops may feature a ‘scratchpad’ which essentially does the same thing – the equivalent of lowering a window, hiding it from sight without opening another workspace, keeping it open in the background, ready to be recalled by a keybind. Even given a scratchpad, multiple workspaces are an inevitability in tiling desktops.

An additional compensating feature in tiling desktops is the ‘stacking’ or ‘tabbed’ mode. In this mode, the workspace does not create new gradually shrinking tiles when new apps are opened. Instead, every new app opens up maximised. Thus you always face a single maximised frame at a time, and to get to any other app, you switch to another maximised frame. This makes actually pretty good sense on small screens, such as netbooks.

From the user’s point of view, the choice between tiling and windowing first boils down to whether the user prefers mousing or keyboarding. Mousing is much more limited on a tiling desktop. Keyboarding is essential.

Moreover, not all windowing features are easy to re-create on a tiling desktop. For example, I personally began immediately to miss proper cycling, by which I mean switching between all apps without regard to their position on the screen or location on workspaces (Alt+Tab). The tiling desktops I tested preferred to recognise directional cycling, i.e. you have to know whether the app you want is to the left or right or up or down, and the number of workspace where it’s located. So, it’s important to remember where you open up things, perhaps by making workspaces topical, like “Internet” or “Office” or “Games”.

In summary, there are some very interesting features in tiling desktops which may make you switch from a windowing desktop for greater productivity. Or, if not switch, you may discover features that you may want to re-create in your familiar windowing desktop, for example always maximise windows in Openbox. And there’s a link available to a tiling window manager demonstration.

Four tweaks for .bashrc

Tweak #1

To enable arrow keys to search history for the ending of a half-typed line.

  bind '"\e[A": history-search-backward' bind '"\e[B": history-search-forward' 

Usage: Type something in terminal that you know is the beginning of a long command line that you occasionally need. Arrow keys up and down should complete it.

Tweak #2

Alert in OSD when a process ends.

alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'

Usage: cmd; alert where ‘cmd’ is an arbitrary command that performs a process, e.g. wget.

Tweak #3

An archive extractor without installing another program.

ext () {   if [ -f $1 ] ; then     case $1 in       *.tar.bz2)   tar xjf $1   ;;       *.tar.gz)    tar xzf $1   ;;       *.bz2)       bunzip2 $1   ;;       *.rar)       unrar x $1     ;;       *.gz)        gunzip $1    ;;       *.tar)       tar xf $1    ;;       *.tbz2)      tar xjf $1   ;;       *.tgz)       tar xzf $1   ;;       *.zip)       unzip $1     ;;       *.Z)         uncompress $1;;       *.7z)        7z x $1      ;;       *)           echo "'$1' cannot be extracted via ext()" ;;     esac   else     echo "'$1' is not a valid file"   fi } 

Usage: ext <file>

Tweak #4

Colors for man pages, Gentoo style.

  man() {         env \                 LESS_TERMCAP_mb=$(printf "\e[1;31m") \                 LESS_TERMCAP_md=$(printf "\e[1;31m") \                 LESS_TERMCAP_me=$(printf "\e[0m") \                 LESS_TERMCAP_se=$(printf "\e[0m") \                 LESS_TERMCAP_so=$(printf "\e[1;44;33m") \                 LESS_TERMCAP_ue=$(printf "\e[0m") \                 LESS_TERMCAP_us=$(printf "\e[1;32m") \                         man "$@" } 

Usage: Open a man page and notice the difference.