Shinobu’s Secrets

October 26, 2009

Auto-update/make/compile script for Lilypond: Autolily

Filed under: Lilypond, Linux, Ruby — Shinobu @ 1:59 am

I’v so far used Lilypond twice to make nice, clean music of some classical pieces. If you don’t know what Lilypond is already, it is basically LaTeX, but for music. Since the music notation style is almost always the same across many different genres, LaTeX’s “what you see is what you mean” philosophy applies particularly well to your sheetmusic-making needs.

The basic way you work is — create an .ly file pursuant to the lilypond format, then save it, then call “lilypond [filename]” on it from the terminal, which will generate a .pdf, .ps, and .midi output all for you (that is, if you have a “\layout {}” and also a “\midi {}” in you “\score {}”). If you have dual monitors, then you can open up the .pdf file with evince, and then evince will automatically update to the latest .pdf version by itself (no need to close and re-open the same generated .pdf file).

This workflow is nice, but it could be better. For one, it takes time to switch windows and invoke “lilypond [filename]” every time you want to see a small change done. For me, I like to make sure at least every 1/2 measure or so that what I put in is correct. Thus, switching back and forth between all these windows every 30 seconds makes the whole process very time consuming.

So I wrote a small ruby script (I call it “Autolily”) to automatically invoke lilypond for me:


 1 #!/usr/bin/ruby
 2 #===============================================================================================================#
 3 # Program name: Autolily                                                                                        #
 4 # LICENSE: PUBLIC DOMAIN                                                                                        #
 5 # This program takes 1 argument, the name of a lilypond file (*.ly), and watches it for changes every 1 second. #
 6 # If there has been any change, it simply calls lilypond on it to create a new .pdf/.ps/.midi of it.            #
 7 #                                                                                                               #
 8 # Place this script somewhere, like in ~/scripts                                                                #
 9 # Then, open up a terminal and call it like so: ~/scripts/autolily.rb [lilypond file]                           #
10 # Be sure to call it from the directory where the lilypond file is located -- i.e., don't do [path/to/file]     #
11 #                                                                                                               #
12 # To exit, type CTRL-C.                                                                                         #
13 #===============================================================================================================#
14 
15 if ARGV.size > 0
16     file = ARGV.shift
17     file_data_orig = ""
18     `ls --full-time`.split("\n").each do |line|
19         if line.split(/\s/).last == file
20             file_data_orig = line
21             break
22         end
23     end
24     file_data_new = ""
25 
26     # enter infinite loop -- keep compiling the given lilypond file if it has changed in the past 5 seconds
27     while true
28         # detect the file size and also timestamp
29         lsarr = `ls --full-time`.split("\n")
30         lsarr.shift # get rid of the first line, since that is the size of all the files in the directory
31 
32         # find our file from ls's output!
33         lsarr.each do |line|
34             if line.split(/\s/).last == file
35                 file_data_new = line
36                 break
37             end
38         end
39 
40         # if there is any change detected, run lilypond on it
41         if file_data_orig != file_data_new
42             puts "\n\e[1;4;38;5;226mAutolily: Change detected in given file; invoking lilypond...\e[0m\n"
43             `lilypond #{file}`
44             file_data_orig = file_data_new
45         end
46         sleep 1
47     end
48 else
49     puts "No .ly file specified.\n"
50 end

This very simple script is an infinite loop which takes snapshots of the output of the "ls" command every second, and monitors any changes. Only the output line for the given lilypond file is monitored. Whenever this single line changes (any time you save your file, thus changing the modification timestamp of the file), the "lilypond [filename]" command is invoked to generate the .pdf, .ps, .midi outputs.

Now, every single time you save your .ly file, Autolily will run lilypond for you in the background, letting you know of any errors or such (and if you have evince open on the generated .pdf file, evince will update what your sheet music looks like as well).

Memory usage of this script is a bit embarrassing -- I get around 4.5 MB -- but hey, that's Ruby's fault.

Enjoy!

October 4, 2009

Linux Dual Monitor Setup: Nvidia & Xinerama Guide: Rotating just one monitor

Filed under: FYI, Linux — Shinobu @ 10:55 pm

I have 2 LCD monitors (both are widescreen) hooked up to an Nvidia card in Linux. For a while, I rotated both of them into a “portrait” view, because, aside from the other benefits a portrait view can give (to webpages and documents), putting two widescreens on a landscape configuration takes up too much horizontal space.

But yesterday, I decided to take a hybrid approach and put my left monitor in landscape view, but my right one into portrait view — i.e., I only wanted one monitor rotated 90 degrees. Of course, this is fairly straightforward in Windows with the proprietary Nvidia utility, but it takes a little bit of work with Linux. I googled around a bit, and found this page. I couldn’t really understand what was going on by just looking at the sample xorg.conf file on that page, so I decided to write out my usual in-depth explanation on the matter.

First, to get this hybrid approach, you have to use Xinerama, and NOT Nvidia’s popular TwinView utility/configuration. This is because TwinView (in Linux) only allows you to rotate BOTH monitors together in the same direction.

The only thing you have to do is edit your /etc/X11/xorg.conf file. First, if you already have TwinView set up to work in a dual monitor configuration, you have to run sudo nvidia-settings, and then change from “TwinView” to “Separate X screen” under the “X Server Display Configuration” settings, like so:

2009-10-04-133053_914x657_scrot

The reason we do this (if you already have nvidia-settings installed) is because it auto-generates a working xorg.conf for us. The thing is, under TwinView, you just have 1 option for everything in Xorg — i.e., you just have Device0, Screen0, Monitor0, but now with the “Separate X screen”, you have Device1, Screen1, etc. Not only that, but your old, irrelevant TwinView settings will be automatically deleted or commented out, so it will save you a couple minutes of work (and any typos as well — typos will prevent X from booting!). After that, it’s just a matter of tweaking the xorg.conf file to suit your needs. (BTW, the reason why the right monitor looks like it’s not aligned vertically correctly with the one on the left is because of a manual adjustment — it’s the 333 pixel shift adjustment I made; read on below for more on that).

Here is my current, working xorg.conf with just 1 monitor rotated:

  1 Section "ServerLayout"
  2     Identifier     "Layout0"
  3     #Screen      0  "Screen0" RightOf "Screen1" # put it on the RIGHT (other options are Below, Above, LeftOf, RightOf;
  4                                                 # alternatively, you can put an absolute, pixel X and Y offset (so RightOf
  5                                                 # would be 1680 0
  6     Screen      0  "Screen0" 1680 0 # NOTE: Screen 0 MUST be defined BEFORE Screen 1!!!
  7     Screen      1  "Screen1" 0 333 # put this screen on the top left, but adjust it down a little bit to match the portrait screen on the right
  8     InputDevice    "Keyboard0" "CoreKeyboard"
  9     InputDevice    "Mouse0" "CorePointer"
 10 EndSection
 11 
 12 Section "Files"
 13 EndSection
 14 
 15 Section "Module"
 16     Load           "dbe"
 17     Load           "extmod"
 18     Load           "type1"
 19     Load           "freetype"
 20     Load           "glx"
 21 EndSection
 22 
 23 Section "ServerFlags"
 24     Option         "AutoAddDevices" "False"
 25     Option         "Xinerama" "1"
 26 EndSection
 27 
 28 Section "InputDevice"
 29 
 30     # generated from default
 31     Identifier     "Mouse0"
 32     Driver         "mouse"
 33     Option         "Protocol" "auto"
 34     Option         "Device" "/dev/psaux"
 35     Option         "Emulate3Buttons" "no"
 36     #Option         "ZAxisMapping" "4 5" # for the Logitech MX 400
 37 EndSection
 38 
 39 Section "InputDevice"
 40     Identifier     "Keyboard0"
 41     Driver         "kbd"
 42     Option         "XkbModel" "pc105"
 43     Option         "XkbLayout" "us,fr,de"
 44     Option         "XkbOptions" "grp:shifts_toggle"
 45 EndSection
 46 
 47 Section "Monitor"
 48     Identifier     "Monitor0"
 49     VendorName     "Unknown"
 50     ModelName      "Acer X222W"
 51     HorizSync       31.0 - 81.0
 52     VertRefresh     56.0 - 75.0
 53     Option         "DPMS"
 54     Option         "Rotate" "Right" # for portrait mode
 55 EndSection
 56 
 57 Section "Monitor"
 58     Identifier     "Monitor1"
 59     VendorName     "Unknown"
 60     ModelName      "Acer X222W"
 61     HorizSync       31.0 - 81.0
 62     VertRefresh     56.0 - 75.0
 63     Option         "DPMS"
 64 EndSection
 65 
 66 Section "Device"
 67     Identifier     "Device0"
 68     Driver         "nvidia"
 69     VendorName     "NVIDIA Corporation"
 70     BoardName      "GeForce 8800 GTS"
 71     Option         "RandRRotation" "on"
 72     BusID          "PCI:1:0:0"
 73     Screen          0 # i.e., the monitor on the RIGHT (physically)
 74 EndSection
 75 
 76 Section "Device"
 77     Identifier     "Device1"
 78     Driver         "nvidia"
 79     VendorName     "NVIDIA Corporation"
 80     BoardName      "GeForce 8800 GTS"
 81     BusID          "PCI:1:0:0"
 82     Screen          1 # the monitor on the LEFT (physically)
 83 EndSection
 84 
 85 Section "Screen"
 86 
 87     Identifier     "Screen0"
 88     Device         "Device0"
 89     Monitor        "Monitor0"
 90     DefaultDepth    24
 91     Option         "metamodes" "DFP-0: 1680x1050 +0+0"
 92     SubSection     "Display"
 93         Depth       24
 94     EndSubSection
 95 EndSection
 96 
 97 Section "Screen"
 98     Identifier     "Screen1"
 99     Device         "Device1"
100     Monitor        "Monitor1"
101     DefaultDepth    24
102     Option         "metamodes" "DFP-1: 1680x1050 +0+0"
103     SubSection     "Display"
104         Depth       24
105     EndSubSection
106 EndSection
107

Probably the most important options are the “Screen” options under the “ServerLayout” section — these define which monitor starts where, and the relationship between the two monitors. The “Screen” options are defined by a X-axis (horizontal) and Y-axis (vertical) offset — you can only use positive numbers, I think, and so this means that if a screen is defined as “0 0″, it is on the top left corner of the imaginary monitor “plane,” so to speak. I.e., increasing the X-axis offset moves your screen to the right, whereas increasing the Y-axis offset moves your screen down. For me, my left monitor is slightly adjusted down by 333 pixels, so that it matches up smoothly with my rotated monitor on my right (my setup, physically, looks like a sideways “T”). I’m not sure if the “RandRRotation” option is necessary — it probably is not — I’m too lazy to check after fiddling with my xorg.conf all day yesterday. The other options should be self-explanatory, along with the comments.

Here are some of the not-so-obvious details: for me, my “DFP-1″ is my LEFT monitor and “DFP-0″ is my RIGHT monitor. Apparently, the “primary display” is by default DFP-o (e.g., in Windows, the Nvidia utility detects DFP-o (my RIGHT monitor) as screen “1 of 2″, so I have to manually set DFP-1 (2 of 2) as my primary screen) — the only reason why I have it like this is because for some reason, my BIOS stuff shows up on DFP-1, and not the default “primary” DFP-0, and I’ve always liked my BIOS to show up on my LEFT screen by default — hence the reason why DFP-1 is on my left and DFP-0 is on my right. I hope that made sense. It probably didn’t, so here is a screenshot:

2009-10-04-141105_2730x1680_scrot

Each monitor has a resolution of 1680×1050, but now, my virtual desktop has a 2730×1680 resolution (1680 + 1050 = 2730). DFP-0 is physically rotated so that the bottom side sticks out to the far right — i.e., it’s rotated counter-clockwise 90 degrees — so that the clean, button-less bezel of its top area matches up nicely with the unrotated DFP-1.  And so, we rotate “Right” under the “Monitor” section for Screen 0. This is probably the most sensible way for most people, since almost all monitors that do have buttons at all (to make an uneven, fatter bezel where the buttons are) have them at the bottom of the monitor.

Here are the advantages that you get with Xinerama in the above setup:

  • Moving the mouse from the right to the left is always continuous and seamless. This is even true when moving from the far edges of the portrait monitor into the widescreen one (see notes in screenshot). Finally, the virtual screen behaves EXACTLY like how the monitors look in the real world. (This behavior is available in Windows; however, there are two shortcomings that are not found in Xinerama: (1) when the mouse is on the top or  bottom edge of the portrait monitor, your mouse becomes “stuck” and does not transition smoothly over to the widescreen monitor on the other side (see screenshot above); (2) even though you can adjust the monitors by simply dragging the icons around (which is very user-friendly, I must say), the adjustments are very course and you cannot adjust things down to the last pixel.)
  • Maximizing a window maximizes to the monitor’s area (i.e., the window maximizes up to either the landscape or portrait view), and not the big, virtual landscape of 2730×1680 pixels; even the applications behave intelligently!

A (temporary) disadvantage:

  • Since I’m using Xmonad as my window manager, popup dialog boxes automatically spawn to to the top-left of the virtual screen — i.e., if they’re small enough, they fit entirely into the unviewable area on the top edge. I have to manually flatten the image into the tiled area to see the contents of it. However, this is Xmonad’s fault, and there is probably a hack out there to fix this sort of thing. Even so, since I don’t really use GUI applications that have a lot of popup dialog boxes in the first place, this is a non-issue.

For a long time I thought that Xinerama was an ATI thing, but apparently, it works for Nvidia as well. The xorg.conf layout looks much nicer, and simpler with Xinerama, and is much more flexible with it (e.g., the 333 pixel shift). If you change the few lines in my xorg.conf above that deal with rotations, you could even do without TwinView as well and just use Xinerama for a basic dual-head setup without any rotated screens.

September 14, 2009

Nvidia & Rotated Screen Partial Workaround

Filed under: FYI, Linux — Tags: — Shinobu @ 6:51 am

Currently, there is a bug in the latest Nvidia drivers for Linux. It is the bug described in the following threads:

I suffer from the same “border anomalies” because I too, use Xmonad and Nvidia drivers, with two rotated screens. I lived with the annoyance for a few months (I even emailed Nvidia a bug report), until, by accident, I discovered a partial workaround — for all urxvt terminal windows. Since I usually do all my important work in urxvt terminal windows anyway (only exceptions being firefox and maybe OOo Writer), it really is a lifesaver. The fix for urxvt windows is as follows: in your ~/.Xdefaults file, put in the following property for urxvt’s resources, like so:

urxvt*depth: 32

For some reason, this fixes the strange border behavior completely for all urxvt windows in Xmonad. I stumbled on this workaround when trying to make my urxvt windows transparent (which don’t work for me — probably because I use xwinwrap to play a screensaver permanently in the background).

BTW, I also use the option “urxvt*fading: 33″ to make inactive windows fade out a bit, even though this setting is a bit buggy at the moment (probably as a result of the xwinwrap thing and also how Nvidia’s drivers are still messing things up in the first place). Still, the fading option is worth a try if you haven’t done so yet — it’s much faster to recognize active urxvt windows than from just using xmonad’s border’s alone (I use a 1-pixel wide white/black border in xmonad).

August 24, 2009

Xwinwrap + Xmonad = Less Deadness

Filed under: Linux — Shinobu @ 8:36 pm

If you use Xmonad, you’ll notice that there is just a dark, black screen for the background on any unused workspace. I must admit, it didn’t bother me much at first, but after a couple of months it got really boring. My computer felt very quiet, and very… dead. I then considered setting up a wallpaper or something to make my desktop look more engaging. Though it is certainly possible to spice it up with a simple background image/wallpaper, it is also possible to put up a movie or screensaver (or any other program). How, you say? With Xwinwrap.

I actually use shantz-xwinwrap-bzr from the AUR (Arch Linux User Repository) to set up a screensaver in the background. Specifically, I use the following call:

xwinwrap -ov -fs -ni -- /usr/lib/xscreensaver/cubicgrid -root -window-id WID -delay 10000 -speed 0.5 -ticks 35 &

This displays the “cubicgrid” screensaver, which is part of the xscreensaver package. The beauty of xwinwrap is that you can use not just a screensaver, but any other program with it. For example, you could, if you wanted, play a movie (or a playlist of movies) in the background, constantly. Though your monitor would then resemble a PC from BestBuy or Costco, playing movies in the background is certainly possible. The only cons are:

  • Uses 5-10% of your CPU, depending on what program you are running.
  • If you are using a standard Desktop Environment like KDE, Gnome, or XFCE, all of your desktop icons will not be displayed, as they will be underneath the xwinwrap window (although you could still see them via transparency — though I have not done this myself).
  • “Cool” effects become a bit boring after a while (the xmatrix screensaver, for example, looks cool for about 5 minutes, but then gets annoying — maybe this is just me though).

I guess a more traditional approach to this technique would be to set up a slideshow of your family’s digital photo album, if you have one. The possibilities are endless.

June 21, 2009

Arch Linux: Clean up those .pacnew and .pacsave files

Filed under: Linux — Shinobu @ 12:55 am

Once in a while, pacman gives messages about some system config file, and the creation of either a .pacnew or .pacsave file (or sometimes a .pacorig file). The reason why this happens is because your system upgrade results in conflicting configuration files — pacman is smart enough to realize that it would be very dangerous to simply overwrite your configuration files automatically with the new ones from the newer package(s). A good example is GRUB’s menu.lst file — you certainly would NOT want to delete the old (unupgraded) one, since it holds all your valuable data about which partition to boot from, and as well as any other operating systems you use under GRUB. So, how should you take care of them — after all, the newer config files DO often contain newer settings and options.

The answer: install the yaourt package from AUR if you haven’t already. Then, issue the command yaourt -C. This will take care of all those pesky config files via an interactive shell session. Yaourt will let you view the original config file, and the .pacnew or .pacsave variant of it, using a variety of programs — including gvim and vim. I use gvim because my default colorscheme in vim is too dark for displaying the diffs properly. Simply do CTRL + W, W in normal mode to switch between the two windows (copy and paste to quickly merge long sections).

You should get in the habit of doing yaourt -C every time you encounter a message about a .pacnew or .pacsave.

June 7, 2009

Tips For the Novice Linux User (Use the Shell)

Filed under: Linux — Shinobu @ 11:43 pm

This post will be updated periodically (or even edited entirely) to reflect my currently knowledge of Linux. It’s mainly intended for people who’ve just gotten into Linux, and to help them know some essential things/config files about Linux. I am NOT a Linux/Unix expert — I merely present the following material to the best of my knowledge, an experience thus far, of using Linux.

The basic Linux layout for the modern user:

Whether you’re using Gnome, KDE, XFCE, etc, your system looks like this:

System -> X (aka X.org or xorg) server -> User Input/Output

As you can see, the X server acts as a bridge between you and the system — mainly in the form of a (pretty) graphical interface. I’ve worked with Ubuntu, Xubuntu, and Arch Linux, and they all use the 7th TTY (aka “virtual console”) for where the X server displays its out put. (That’s right, when you’re looking at X you are looking at the output on CTRL + ALT + F7; you can do CTRL + ALT + F1 through F6 to see 6 other places where you can log in and use Linux on a purely text-based, non-graphical level!! Try it out!) Some newbies get confused and do not know how to diagnose problems if their X server suddenly stops working (usually due to an upgrade to the latest, barely tested X version), and their computer doesn’t boot into the desktop environment (DE). It is important to realize that X is *not* a requirement to fix most if not all of your problems. As I’ve hinted above, you can switch to a different TTY/virtual console any time to access everything on a text-based level. This is a handy feature, since everything in Linux is text-based at the most fundamental levels.

Some vocabulary first:

Terminal/console (aka command-line interface, or “CLI”): a terminal or console is the text-based, “DOS prompt”-like interface that most Linux users love to use from their Gnome/KDE/other X environment (it emulates the TTY/virtual console described above, but from within the X environment — a useful feature indeed!). The “terminal” application on most desktop environments (DE’s) point to either gnome-terminal, xfce4-terminal, or some other terminal installed with the base installation. If you don’t have a DE, it’s still likely that you use X (I myself use Xmonad, which itself depends on X), in which case xterm will be installed. There are a plethora of terminal emulators you can choose from — I use the 256-color enabled version of rxvt-unicode, since it handles unicode text and window-resizing very well.

Shell: a shell is the program between your TTY/virtual console/terminal application and you.

System -> TTY/virtual console/terminal app -> Shell -> (text-only) user input/output

Most systems use the Bourne Again Shell or “bash” by default. Here again, there is a plethora of alternatives to choose from: zsh, fish, csh, tcsh, ksh, etc. I use zsh by default (it is the “login” shell for my username — i.e., whenever I go to a TTY/virtual console with CTRL + ALT + F1 through F6 and log in, the zsh shell takes over by default), since it has some really painless tab-completion (pressing TAB to cycle through various options) and prompt customization (a prompt is what you see after pressing “enter” — usually the location of your present working directory along with your username, and the name of the machine (aka “hostname”) you are on). Once you start up a shell session, either via a virtual console, or via a terminal emulator from the X environment, you are placed into a directory — usually your home directory (the shorthand is the “~” character). You can move around with “cd ..” to go up 1 parent directory, or “cd [directory name]” to go to that sub-directory.

Command: a command is a word that you type into your shell-of-choice, which invokes some other program or does something to the system to either (1) change the system or (2) produce some output. For example, the “ls” command outputs all the contents of your current directory.

Argument/parameter: an argument is a word that follows a command. E.g., for “echo hi”, echo is the command, and “hi” is the argument. An argument can be a flag (aka “option”), which is usually a hyphen with a letter, like “-r”, or two hyphens followed by a full word like “–option”.

Shell scripts: a shell script is a series of commands, written into a text file, to be used over and over again to save time. It can contain not just commands, but also loops, if/else statements, etc to become even more useful. The first line looks like “#!/bin/sh” in 99% of cases (and you’ll see that /bin/sh is symlinked to /bin/bash). The “#!” is called the shebang (I did not make this up!). The shebang is very important, as it tells Linux which program to use to execute those commands. That’s right, you can write a script in not just the language used for shells, but also Python (the programming language), Ruby, Perl, etc.

And now, some tips:

TIP #1: USE THE SHELL

Most people will say that the shell is “powerful” and that’s the reason why they like to use it instead of some GUI-based solution. While I agree that the shell is very powerful, the real reason why I like to use the shell is because it represents the closest distance between me and the computer. If run from within an X session, the shell essentially removes the graphical layer that separates me from the system. Even running a non-text-based program by invoking it from the shell has an advantage: you can see exactly what the program is thinking, because most programs output additional messages to the shell, but not to the GUI — a prime example is mplayer.

Using the shell, of course, requires some knowledge of basic commands. I already mentioned a couple: cd to change the current directory, and ls to list the contents therein. A really useful command you’ll use throughout your Linux experience is the man command. Type “man [some command/program name]” to access that command/program’s manual. Apparently, all manuals are grouped into 9 different sections — the most notable are section 1 for executable programs or shell commands (such as cd or ls) and 3 for C programming commands. Since cd is a shell command, you can do man 1 ls. However, man is smart enough to accept just man ls, since ls is unique. If a manual page has an ambiguous name in that the same name appears in multiple man sections, you’ll need to type man [section] [command/name] to get what you want. If you’re not sure whether the command you are typing has multiple entries in different sections, you can use the whatis command to tell us all the manpage sections with the given name. You can navigate through man’s output (called the “manpage”) with “j” for scrolling down, “k” for scrolling up, CTRL – D/U for scrolling multiple lines down and up respectively, and PAGEUP and PAGEDOWN to go up and down a whole page. Press “q” to exit. For some manpages, you’ll see a “SEE ALSO” section, e.g., “mandb(8)” or “less(1)”. The number in parentheses is simply the section number. So to go to mandb(8), you must type man 8 mandb. As both man and whatis are themselves commands, you can do “man man” or “whatis whatis” or “whatis man” or “man whatis” to get more information about them.

Note: the output of the man command is actually “piped” into the less program, and what you are actually interfacing with is the less program (i.e., all the hotkeys I described above for “man” are actually the hotkeys for less). All less does is it shows you all the given text, while still allowing you to “scroll back” to earlier lines and back down again, interactively. Because manual pages are often hundreds of lines long, outputting it directly to your shell would mean you’d have to scroll up and down from your shell — not a very pleasant experience, although it is doable. Piping long, multiline text it into less makes the experience more manageable. Another case where less is useful: say you have a directory with 500 subdirectories. Typing ls by itself would be a bit too much. Instead, type ls | less, and now it’s much more manageable. The pipe “|” operator is useful whenever you want to give one program’s output and feed  it to another program.

Here are some other basic shell commands (use man to find out more about these commands):

  • du: to find out how much disk space is being used
  • df: to see how much free disk space is remaining
  • rm: to delete a file (this is permanent — ou cannot ‘undo’ this command, so be sure to make a backup if you want to get it back later); to delete a directory (and thus all its contents), type rm -rf dirname
  • mv: renames a file or directory; in the case of a directory, you can move it to a different location if you provide a nested path (e.g., “mv dir ../dir2″ — this says “go up one directory, and if the directory “dir2″ exists, move dir into dir2, otherwise rename dir into dir2); mv is useful because it is a move/rename operation combined into one command, depending on whether the renamed-to argument conflicts with an existing file/dir name
  • cp: copies files from one location to another (e.g., “cp file file_backup” creates a copy of file, names it as “file_backup”, and places it in the current directory); to copy everything within a directory, do “cp -r” (the -r flag stands for “recursive”)
  • ln -s [original file] [hot clone/ghost name]: creates a symbolic link — symbolic links are very useful: e.g., if you symlink “/bin/copy” to “/bin/cp”, then typing “copy” is exactly the same as typing “cp” for the copy command, and will take all the same flags as the regular cp. I’ve called the second argument a “hot” clone/ghost because modifying the symlink affects the original (except for the “rm” command). (If you’re a C programmer then, suffice it to say that ln -s creates essentially a new pointer to the given object). Another example: if you symlink a name to another directory, then cd-ing to that name will move you into that other directory, but Linux will treat that other directory as being present in the same parent directory as the name provided. I.e., it’s effectively a ghost/clone. Another example: say you are symlink-crazy and want to have a particular file to be present in every directory in the entire system. You can do this by creating a symlink to that particular file for every directory on the system — this would result in creating a ghost image of that file in every directory. You can do whatever with this ghost image, and it will affect the original file. The only exception is the deletion of that ghost image with the “rm” command — it will NOT delete the original file; it will only delete the symlink itself. If you want to see some good examples of heavy, nested ln -s usage, simply go to your /dev directory. Your /dev/cdrom file is most likely a symlink pointing to another file. (For all of my Arch Linux machines, I discovered that /dev/cdrom, /dev/cdrom0, /dev/cdrw, /dev/dvd and /dev/dvdrw ALL point to the single device file /dev/sr0, for the CD/DVD burner.)
  • scp: acts just like cp, but over to a different machine over a network
  • vi or vim [text file]: invokes vi or vim, depending on which one is installed, to edit a file; learning to use vim is a smart investment of time; note that a file in Linux is either text-based or binary. (Text files are the regular files that humans can read (it has words in it), while binary ones are things like picture files (.jpg), music/video files (.mp3, .mkv), and program executables (in Linux, they have no file extension). A text file need not have an extension.)
  • touch [filename]: if the given filename is not present, it creates an empty text file with that name — otherwise, it updates the “last modified” metadata for that file to the current time; using touch is useful if you want to create a series of “placeholder/nameholder” files that you want to update/edit later, but not now.
  • poweroff: turns the computer off
  • reboot: turns the computer off, then back on again
  • ssh: connects you to a different machine as a different user. ssh is arguably one of the most useful commands in the Linux world, as it allows you to remotely access a networked machine’s shell. ssh is helpful because it gives you a cryptographically secure shell connection to modify systems remotely. This means that you can reboot a computer on your home network without physically going to that computer — you can just ssh to it, and then type “reboot”
  • eject: this is here for illustrative purposes — the eject command simply ejects the CD tray of the given optical device (and closes it if it is already open); it’s quite interesting in the same sense as the poweroff and reboot commands, in that it affects via software the hardware orientation of your computer. Isn’t cool to realize that, you can eject the CD tray of a computer on the other side of the world (as long as you can ssh to it)?
  • sudo: this is another command you’ll be using for a long time — it executes whatever that follows it as if it were from the root user (the root user is a “user” that is installed with every Linux installation, and lives in the /root directory, who has the power to change core system files that are off-limits for normal “regular” users). If you forgot to prepend your argument with “sudo”, and Linux complains about permission issues, just do “sudo !!” and the “!!” will act as an alias for the last-typed command. Oftentimes, you’ll encounter statements like “do X as root” or “with root permission, do Y” — all this is saying is that you must run the command as if you were the root user — either by logging in as root, or by using some other method such as invoking the “sudo” command.
  • su -m: this command changes the current user to the root user, while preserving the current shell (otherwise, the default shell of the root user, usually bash, will be used); this command is useful if you want to run a series of commands for modifying/accessing core system files in root-owned directories, like the /etc directory.
  • UP ARROW: this is not really a command, but a hotkey present in all shells: pressing the up arrow key will go back to the previous command you typed; the size of the command history depends on the history size variable of the shell, which can be changed (for zsh, it’s defined in your ~/.zshrc file). The DOWN ARROW is the logical opposite.
  • find: finds files/directories. Here’s a concrete example: “find -maxdepth 1 -name document” searches for a file named “document” in the current directory; if it is found, it outputs the path to the document. If not found, it outputs nothing.

Some things (quirks) about the shell:

  • Everything is case sensitive. And I mean everything. “CD” is different than “cd”. The flag “-f” is different than “-F” (unless the command/program treats them the same way). A file called “file” is different than a file called “FILE” or “File” or “fiLe” or “filE”, etc. You get the idea.
  • The “~” (called “tilde“) character: this character is an alias for your home directory; so if your username is “joe”, then the “~” character, as interpreted by your shell, is the SAME as “/home/joe”. Indeed, typing “~” is a lot easier, and faster, than /home/joe.
  • The “.” (period) character: this character literally means “full path to current directory.” For example, if you type “cp file .”, it will fail because it really means “copy file into the present working directory”, and the name “file” is already present. The “.” character comes into play in two frequent situations, however: (1) when you want to run a program located in the present working directory (see the discussion about “./” below), and (2) when you want to create a symlink in the current directory (e.g., “ln -s /full/path/to/some/file/or/directory .” creates the symlink to some file or directory in the present directory, keeping the same name as the target file/directory.
  • The “/” character: by itself, it means “the highest directory in the system”; e.g., “cd /” will take you to the highest directory that contains /etc, /root, /home, etc. If this character follows a word, it’s simply a (sub)directory delimiter. Combining “.” and “/” gives us “./”, which literally means “full path to current working directory”.
  • The “*” character means “everything in this directory.” This is useful, for example, if you want to delete every file in the current directory, but keeping the current directory. You could just go up 1 directory, and invoke “rm -rf [directory name]“, but that would delete the directory itself as well. If the “*” character is mixed up with letters, it acts as a regular expression that matches any character. For example, “rm *.mp3″ will delete every mp3 file in the current directory. If you want to use the “*” character as an argument to pass to a program, use “\*” instead.
  • The “\” character is the escape character. This is used to disambiguate identical-looking characters that mean different things. For example, say you have 3 files “hello,” “there”, and “hello there”. You want to edit the “hello there” file. Typing “vim hello there” would not work, as vim would interpret “hello” and “there” as two different files; the proper way is “vim hello\ there”. Here, the “\” character is followed by a space, serving to disambiguate the space character to mean “the space between the “hello” and “there” in the “hello there” file, and not the usual meaning of an argument list delimiter. If you have a long file name with a bunch of spaces in between, then typing all those “\” characters might be confusing; in this case, you could just enclose the wordy file with double quotes, so that vim “a filename with a lot of spaces in between” works as expected.
  • Your shell has direct access to so-called “environment variables“. You can invoke the “printenv” program to list those environment variables set in your current shell session by typing “printenv” (“env” does the same thing if no arguments are supplied). Environment variables are simply configuration settings for different aspects of your system, that are used by programs (including shells!) to customize your user experience. Perhaps the most common variable is HOME, which is the path to your home directory. Another common one is PATH, which is simply a list of directories that have executable programs in them (like /bin or /usr/bin); any program that resides in a directory listed by PATH can be executed directly in the shell without specifying the full location of that program. E.g., you can type “/bin/cp” to invoke the cp program, but you can just as easily type “cp”, since the “/bin” directory is defined in PATH. (Note: if you want to invoke a program that is in your current directory, then prepend it with “./” — e.g., if you downloaded a program that is self-contained, then going into that program’s directory and typing “./program_name” will invoke that program; in fact, the use of “./” here is required as it ) Environment variables really start to shine when you use them in shell scripts.

TIP #2: BACKUP YOUR ESSENTIAL SYSTEM FILES

You should always keep your eye on your core system files. The most common ones are:

  • /boot/grub/menu.lst: this holds the file that the GRUB bootloader reads on bootup to boot to the proper operating system; this file is especially important in dual-boot machines that have multiple, different operating systems installed
  • /etc/X11/xorg.conf: this file is read by the X server each time it starts — among other things, here you can customize your keyboard’s locale (if you have an Apple keyboard, for example, you can tell Xorg that you are using such a keyboard, so that X can correctly interpret all the keys on the keyboard), as well as touchpad settings for synaptic touchpad users (how fast the touchpad scrolls, whether touchpad tapping is enabled, etc.)
  • ~/.xinitrc: this file is executed by X once the /etc/X11/xorg.conf contents have successfully loaded, and all commands are executed as the logged-in normal user. Think of the .xinitrc file as a file that contains a list of shell commands that you want executed automatically for you every time you log into your computer. Usually, this file is used to either set environment variables for the entire X session, or to start daemons that require special arguments and settings (e.g., SCIM, urxvtd, xscreensaver, etc). For example, if you want to set your keyboard’s repeat key rate to a certain speed, then you can hav “xset r rate 400 50″ in your ~/.xinitrc file, and each time X is run it will set the key rate to the specified rate. The so-called “rc” files are configuration files, and here “xinitrc” stands for the configuration file for the xinit command (the command that is executed to start the X server — either manually or automatically if you have a DE; startx is a front end to the xinit command).
  • /etc/fstab: this is the file that Linux uses to mount partitions/devices onto your system. The basic format of every line is [device or partition] [mount point directory] [options]. Your device can be, for example, /dev/sr0 for your CD/DVD burner, or a UUID (a hexadecimal-based string that is unique to a partition on a hard drive). The mount point directory simply represents what the mounted device looks like, in terms of directories; e.g., I have a second hard drive partition whose mount point is “/mnt/hd2backup1″ — here, if I go to /mnt, I will see a directory called “hd2backup1″, which contains all the contents of this hard drive partition. For ex-Windows users: a partition in Linux does NOT start with a capital letter followed by a colon, like “C:” or “D:”. Since everything in Linux is a file or directory (a directory being nothing more than a file that points to a collection of other files), even a hard drive partition does not deserve special distinction, and is merely, following my example above, a subdirectory under the /mnt directory. Do realize that the mount point directory is customizable — you can call it anything you want, as long as it exists on the system. For example, I have my /dev/sr0 and /dev/sr1 devices (my 2 CD/DVD burners) mounted to /mnt/media-sr0 and /mnt/media-sr1, respectively, as I find mounting them to the default /media directory a bit confusing (we mount devices to use them — we don’t “media” them).
  • /etc/rc.local: this file is merely a shell script that is run before anything else is run on bootup — even before xorg.conf or ~/.xinitrc is read! The counterpart to this file is /etc/rc.local.shutdown, which is a shell script that executes, appropriately enough, on shutdown.
  • /etc/sudoers: this file contains a list of users who can use the “sudo” prefix in their shell commands to run the command as the root user. It also can contain a list of executables that can be run by the specified normal user, so that the executable is run as root but without the (sometimes annoying) password prompt. This is useful if you run a root-level command often, but find the required password-typing a bit tedious (for example, both the poweroff and reboot commands require root user permission, since we want to avoid the situation where one user to turn off the computer if another user is also logged into the same machine  (Linux is a truly multi-user-concurrency system!) — however, if you are the only user on the system, then you can avoid password prompts by including the poweroff and reboot commands in the /etc/sudoers file). The preferred way to edit the /etc/sudoers file is with the command “visudo” as root.

TIP #3: KNOW YOUR SHELL

Since your time spent at the shell will grow more and more as you become more familiar with Linux, you should try to learn how to make your shell more useful than simply treating it as a box to dump your commands. A good place to start is editing your shell’s configuration file. For zsh, it’s ~/.zshrc. Whether your shell is zsh or any other shell, the most obvious place to start is aliases. An alias is simply a word that acts as a much different (and usually more complicated) full-fledged command. E.g., I have “k” set up as “cd ..”, “kk” aliased to “cd ../..”, “kkk” aliased to “cd ../../..”, etc. It’s a lot easier and faster to type “k” than the more wordy “cd ..”. I also have “discon” aliased to “sudo mount /dev/sr0″ — and since I have the mount command in the sudoers file, I can just type “discon” and it will mount the CD or DVD to the given path (the command here only works without specifying the mount point directory because the mount point directory for /dev/sr0 is defined already in my /etc/fstab file). Similarly, I have “usbon” aliased to “sudo mount -w -t vfat -o uid=shinobu,gid=shinobu /dev/sdc1 /mnt/media-flash” to mount USB thumbdrives easily with just one word. My aliases “discof” and “usbof” unmount the above devices, respectively.

Once you get comfortable with your shell and that big black command-line prompt does not get so intimidating any more, you should consider learning how to write shell scripts. If you find the bash scripting language too arcane in appearance, consider using Python or Ruby instead — both of these languages can execute shell commands easily, with the added benefit of an extremely simple, low-learning-curve syntax. The biggest reason for learning how to write a shell script is this: you can automate anything. For example, the mp3 replay gain scripts I mentioned here owe their usefulness to bash/Python scripting. If you know how to use cron, then you can automate something to happen on every specified interval — be it hours, days, months, even years!

April 12, 2009

Disable touchpad tapping in HP G60 on Linux

Filed under: Computer Hardware, Linux — Shinobu @ 8:20 pm

I scoured all over the internet for a good hour and a half before finding the solution. To disable touchpad tapping for the G60, you need to: (1) enable synaptics from /etc/X11/xorg.conf, and (2) use a very specific, hard-coded device option to point to your touchpad device.

Here is the relevant portion of my xorg.conf for the HP G60 (G60t-200, to be exact — at least according to the sticker on the bottom; NOTE: I’m using the latest Xorg 1.6, but that shouldn’t really make any difference for our purposes here):

Section "ServerLayout"
    Identifier     "X.org Configured"
    Screen      0  "Screen0" 0 0
    InputDevice    "Mouse0" "CorePointer"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice     "SynapticsTouchpad" "SendCoreEvents"
EndSection

Section "Module"
    Load  "glx"
    Load  "dri"
    Load  "dbe"
    Load  "xtrap"
    Load  "extmod"
    Load  "freetype"
    Load  "synaptics"
EndSection

Section "InputDevice"
   Identifier  "SynapticsTouchpad"
    Driver      "synaptics"
    Option        "SendCoreEvents" "true"
    Option        "Device" "/dev/input/by-path/platform-i8042-serio-2-mouse"
    Option        "Protocol" "auto-dev"
    Option        "HorizEdgeScroll" "0"
    Option      "SHMConfig" "true"
EndSection

Notice the italicized lines. The real key here, from what I can tell (I tried copying and pasting many different configs from various forums), is the line

    Option        "Device" "/dev/input/by-path/platform-i8042-serio-2-mouse"

I first got the idea to add the above weird-looking line from a Gentoo wiki page on another HP laptop model. I bet the above format will work for any recent HP laptop, not just the G60. The only difference between the G60 and the Pavilion DV5000 is that the DV5000 uses “…serio-4-mouse”, whereas the G60 uses “…serio-2-mouse.” To figure out this critical “serio” number, use the following command:

less -eX /proc/bus/input/devices

The output for my G60 looked like this (other irrelevant devices omitted):

I: Bus=0011 Vendor=0002 Product=0007 Version=01b1
N: Name="SynPS/2 Synaptics TouchPad"
P: Phys=isa0060/serio2/input0
S: Sysfs=/devices/platform/i8042/serio2/input/input10
U: Uniq=
H: Handlers=mouse1 event10
B: EV=b
B: KEY=420 70000 0 0 0 0
B: ABS=11000003

Notice the italicized line. It says “serio2″. Anyway, the minimal xorg.conf settings work really well — senstivity and acceleration are handled quite nicely by default. Also, tapping is NOT enabled by default, so that’s why my settings do not say anything about it.’

NOTE: The touchpad by default works very well without synaptics (vertical scrolling and all) using the Linux Kernel 2.6.28 and the newer 2.6.29, with Xorg 1.5.3 and 1.6 — however, tapping is enabled by default. The above solution is the only way to disable (the rather annoying and extremely sensitive) touchpad tapping for the HP G60.

Sources:

http://en.gentoo-wiki.com/wiki/Hp_Pavilion_DV5000

http://www.linuxquestions.org/questions/slackware-14/synaptics-touchpad-in-slackware-12.2-on-hp-g60-702809/ (post#4)

April 11, 2009

Useful shell aliases for pacman/powerpill in Arch Linux

Filed under: Linux — Tags: , , , — Shinobu @ 11:49 pm

If you’re an Arch Linux user, you’ll find yourself typing “pacman -Sy <package>” or “powerpill -Syu” a lot. Here are some useful shell aliases (here, they are for Zsh) that I use to make things much, much easier:

alias p='sudo pacman'
alias pu='sudo pacman -Syu'
alias pa='sudo pacman -Sy'
alias pq='sudo pacman -Q'

alias pp='sudo powerpill'
alias ppu='sudo powerpill -Syu'
alias ppa='sudo powerpill -Sy'

And then all I have to type is ppu, and my system is upgraded. Also, I have in my /etc/sudoers file the following:

shinobu exelion=NOPASSWD: /usr/bin/pacman
shinobu exelion=NOPASSWD: /usr/bin/powerpill

This way, I don’t have to type my password every time I want to use pacman/powerpill.

March 31, 2009

Use your /etc/hosts file to save time

Filed under: FYI, Linux — Shinobu @ 7:40 am

I was installing Arch Linux on yet another machine (new laptop), and was pleasantly surprised by a little tidbit in the Arch Wiki pages — specifically the Beginner’s Guide (which is continually improved and updated fanatically by the Arch community). In short, you can alias host addresses in your /etc/hosts file. This can be for web addresses (www.google.com) or addresses on your LAN. Here is the example and explanation given by the wiki page:

“Tip: For convenience, you may also use /etc/hosts aliases for hosts on your network, and/or on the Web, e.g.:

64.233.169.103   www.google.com   g
192.168.1.90   media
192.168.1.88   data

The above example would allow you to access google simply by typing ‘g’ into your browser, and access to a media and data server on your network by name and without the need for typing out their respective IP addresses.”

Putting your hostname aliases in your /etc/hosts file is great, since all of your programs use it. Firefox, your terminal/shell, git, etc. They all reference this file. So if you’re using git, you can do git clone ssh://username@hostname-alias/… to clone a repo from your LAN, as I described in my post here, instead of ssh://username@192.168.0.2/…. So now all of your hosts on your LAN will be much easier to remember. Here’s my /etc/hosts file:

#
# /etc/hosts: static lookup table for host names
#
#<ip-address>    <hostname.domain.org>    <hostname>
127.0.0.1        aether.localdomain    aether
# aliases
192.168.0.20   exelion
192.168.0. 21 luxion.e
192.168.0.22   luxion.w
# End of file

I’ve aliased luxion.e to my laptop’s ethernet adapter, and luxion.w to its wireless adapter. After setting up your aliases in /etc/hosts, you should get in the habit of writing out your (sane) hostnames for all your LAN computers, instead of painfully writing out their numeric IP addresses. (And I’m sure you’d want to alias your hostnames even more with the advent of IPv6 — and its rather long IP address format.)

March 26, 2009

Clean Japanese and Korean Characters in URXVT

Filed under: Linux — Tags: , , , , , , , , , — Shinobu @ 7:45 am

I have files and directories using Japanese and Korean. Unfortunately, urxvt by default does not display these characters nicely (the hangul looks especially ugly) by default. The way to fix this is to have a good set of TrueType fonts for both Japanese and Korean, and to have URXVT use these as defaults.

If you’re on Arch Linux like me, you can install from the AUR the ttf-kochi-substitute and ttf-baekmuk fonts for Japanese and Korean fonts, respectively. (There is also ttf-sazanami and ttf-unfonts-core for more Japanese and Korean fonts, respectively — but here I’m going to use Kochi Gothic and Baekmuk Gulim in URXVT). Now, in your ~/.Xdefaults file, put this in:

urxvt*font: xft:Terminus:pixelsize=14,\
            xft:Kochi Gothic:antialias=false,\
            xft:Baekmuk Gulim

This makes it so that Terminus is used, then Kochi Gothic, then Baekmuk Gulim. It’s good to have Kochi Gothic on a higher priority than Baekmuk Gulim, since Kochi Gothic’s kanji glyphs look much better than Baekmuk’s (and since Japanese words often have kanji in them, whereas Korean files almost always have just hangul in them). Also, the pixelsize defined with Terminus is used for all succeeding fonts below. Now my URXVT looks really nice!

Older Posts »

Blog at WordPress.com.