To schedule a once off command to run sometime in the future: echo "wget url" | at 01:00 % Bash arrays: array=(zero one two) array[3]=three echo "The fourth element of array is ${array[3]}" echo "There are ${#array} elements in array" for example, the following 2 are equivalent: VER=`cut -d' ' -f4 /etc/fedora-release` VER=($(< /etc/fedora-release)); VER=${VER[3]} Note, consider using a more powerful language like python if you need to use bash arrays % In bash one can expand the last parameter used with !$ i.e. if one did `mkdir mydir` then `cd !$` would move to it. Search for "history expansion" in `info bash` for more info. Note this is only for interactive use, it doesn't work in scripts. See also http://www.pixelbeat.org/settings/.inputrc % To display a quick calendar on the console: cal -3 % Data and audio CDs save copy of data cdrom dd bs=1M if=/dev/cdrom | gzip > cdrom.iso.gz create cdrom image from directory mkisofs -r dir | gzip > cdrom.iso.gz burn cdrom image gzip -dc cdrom.iso.gz | cdrecord dev=0,0,0 rip auto tracks from CD to wav files in current dir cdparanoia -B make audio CD from all wavs in current dir cdrecord dev=0,0,0 -audio *.wav make ogg file from wav file oggenc --tracknum="track" track.cdda.wav -o "track.ogg" % If you want to turn off the "clear screen" done by some terminal apps on exit: infocmp $TERM | sed 's/\([rs]mcup=\)[^,]*,/\1,/' > /tmp/$TERM.src tic -o ~/.terminfo/ /tmp/$TERM.src rm /tmp/$TERM.src Remove the resultant file in ~/.terminfo to undo % To setup terminal application foreground colours appropriate for a dark background: ls cp /etc/DIR_COLORS ~/.dircolors vim echo "set background=dark" >> ~/.vimrc Note to change colours for linux virtual terminals setterm -background white -foreground black -store % #what day does xmas fall on, this year date --date='25 Dec' +%A #convert number of seconds since the epoch to a date date --date '1970-01-01 UTC 130204800 seconds' #What time is it on West coast of US #(use tzselect to get TZ to use) TZ="America/Los_Angeles" date % Quickly search word list for prefix look prefix Highlight occurances of word in word list look '' | grep -Fi --color word Lookup word in online dictionaries/info gnome-dictionary ireland % Directory navigation cd - go to previous directory cd go to home directory pushd . put current dir on stack so you can popd back to it (cd dir && cmd) go to dir, execute cmd and return automatically % Handy disk space commands ls -lSr #show files, biggest last df -h #free disk space df -i #free inodes du -hs ... #disk usage of specified files/dirs fdisk -l #show disks partitions sizes (run as root) See also: http://www.pixelbeat.org/scripts/dutop % Handy find commands to check permissions in a web tree find -type f ! -perm -444 #files not readable by all find -type d ! -perm -111 #dirs not accessible by all % Wondering what the optimum flags for your compiler and CPU combination? http://www.pixelbeat.org/scripts/gcccpuopt % Transforming documentation. The following changes the tar docs from man, interactive help and info documentation, to HTML, PDF and HTML respectively. gzip -dc `man -aW tar` | groff -Thtml -man /dev/stdin > tar.html card tar -o- | ps2pdf - > tar.pdf texi2html tar.texi #Note texi is the source format of info docs % A common cause of networking problems on linux is the integrated firewall which is enabled by default. You can easily control it with the following 3 commands: /etc/init.d/iptables st{atus,op,art} Editing of the rules is system dependent, but many use a thirdparty rule editor like shorewall for e.g. % Common Email/IRC acronyms YMMV = Your Mileage May Vary IMHO = In My Humble Opinion AFAIK = As Far As I Know IIRC = If I Remember Correctly BTW = By The Way FYI = For Your Information % For a single user box, adding the following to /etc/fstab, will allow you to `mount /mnt/floppy` etc. as a normal user /dev/fd0 /mnt/floppy auto nosuid,nodev,noauto,user 0 0 /dev/cdrom /mnt/cdrom auto nosuid,nodev,noauto,user,ro,unhide 0 0 % To scroll the console (linux or xterm) use Shift+PgUp & Shift+PgDn % Handy aliases (to add to ~/.bashrc) #Quick dir listing alias l='ls -l --color=auto' #Show the directories in the current dir alais lld='ls -lUd */' #A handy hexdump alias hd='od -Ax -tx1z -v' % Multimedia conversion Use `sox` to convert sound file formats and `convert` for graphics file formats. For e.g. this adds a comment to a jpg file. convert infile.jpg -comment "a comment" outfile.jpg % Have a look at the following for common command line operations http://www.pixelbeat.org/cmdline.html % To view the contents of an archive (tar.gz, .rpm, .deb, ...) use Midnight Commander (mc) (Just hit enter on the higlighted file). This even works remotely (over ftp, fish, ...) Non obvious keys for mc are documented here: http://www.pixelbeat.org/lkdb/mc/html % For useful non obvious keyboard bindings to various linux apps, see: http://www.pixelbeat.org/lkdb/ % If you need to leave a program running after you log out, try screen: http://www.pixelbeat.org/lkdb/screen.html % When you install a package on linux, generally detailed documentation is in /usr/share/doc/$PACKAGE/ and binaries are in /usr/bin/ or /bin. You can get specifics on rpm distributions as follows: rpm -ql -p package.rpm #show where files in RPM would be installed rpm -ql package #show where files in package were installed rpm -ql -f /path/file #show files for package /path/file belongs to % To convert a DOS text file to Unix so that the extra ASCII 13 does not show up and vice versa, the unix2dos and dos2unix commands are very handy. You can do the same thing with sed, tr, recode, ... % Multiple X sessions It is possible to open more than one "X" session on a single box. As User #1 (from console) : $startx -- :0 As User #2 (from console) : $startx -- :1 ... and so on Toggle between sessions with Ctrl+Alt+F(n) and Ctrl+Alt+F(n+1) and so on ... where n is the first free tty (usually F7) vnc or xnest can be handy for the same task also. % To show the dependent libraries for a binary use: `ldd /path/to/binary` % Linux Documentation looking for a command related to a word? Try apropos Already know the command name? Try `man command` or `info command` Keys for man/info are here: http://www.pixelbeat.org/lkdb/info.html Additional documentation for a package is usually stored under /usr/share/doc/$PACKAGE/ % Process managment ps -Af --forest #show all process commands and hierarchy You can send signals using the command `kill -num pid`. The default num is 15 (SIGTERM). `kill -l` will give a list. Note kill -9 should never be used in normal operation. % Multi boot : Installation order For multiboot machine, the OS install order is "dumbest first" dos -> Win9x -> Win NT/W2k -> Linux % Shell auto completion Autocompletion is a feature provided by shells to complete any part command from the console. For different shells these are: Shell csh ksh bash Single option completion Esc-Esc Esc-Esc Tab Unresolved reference menu Ctrl-D Esc = Tab-Tab Note bash has programmable auto completion which can be very handy. % User management on redhat 9 at least has the following tools, going from high level to low level: redhat-config-users user{add,mod,del} vipw redhat-config-users group{add,mod,del} vigr % login messages The file /etc/motd displays a message at every login. To have it change, point MOTD_FILE in /etc/login.defs to another file. Users can suppress this message by doing `touch ~/.hushlogin` % Type [Ctrl+R] in the bash prompt and you will get a (reverse-i-search)`': TYPE THE SEARCH WORD HERE This will show the matching commands executed before. % Console hotkeys Add entries like the following to ~/.inputrc "\e[[A":"lynx\C-M" # F2 Gnome 2 hotkeys Using gconf-editor edit the following keys as appropriate: apps->metacity->keybinding_commands->command_{1,12} apps->metacity->global_keybindings->run_command_{1,12} % File encryption gpg -c file #encrypts file gpg file.gpg #decrypts file Vim has builtin encryption (simple like pkzip). Use ':X' to encrypt your file. Enter a blank password to save a decrypted copy again. % Environment variables VAR=value command #for command only VAR=value #for this shell only export VAR=value #for this shell and child processes Environment variables can never be passed to parent processes It's useful to set environment variables like above in startup files. To get details for bash do: info bash "Bash Features" "Bash Startup Files" % Turn off annoying beeps readline: add "set bell-style none" to ~/.inputrc X: xset b off gnome-terminal: uncheck "Terminal bell" in profile's settings vim: add "set visualbell" to ~/.vimrc % Command execution timing To see how long it takes a command to run, type the word "time" before the command name. % nslookup is obsolete. Use host for DNS lookup instead host www.pixelbeat.org # A record for domain name host -t MX draigBrady.com #MX record for domain name host 192.0.34.16 #reverse dns on ip address host `hostname` #ip address of current sys hostname -i #same as above without DNS % Downloading directly from web To download html directly as text: lynx -dump -width=1000 http://www.pixelbeat.org/vim.tips.html > vim.txt To download any file directly: wget http://www.pixelbeat.org/cmdline.html % Math in shell You can use bc, python, expr etc. to do math in the shell. Note expr can only parse and output integers. precision=2 num1=1.23; num2=3.21 answer=`echo "scale=${precision}; $num2/$num1" | bc` answer=`echo "print '%.${precision}f' % ($num2/$num1)" | python` answer=`expr 1 / 2` % Backing up a directory Backing up a directory preserving ownerships, permissions and links, to another location: cp -a /dir/to/copy /where/to/ or ( tar cf - /dir/to/copy ) | ( cd /where/to/; tar xf - ) Note the previous 2 create the copy dir under /where/to/. If instead you would like just all the contents of copy, do: ( cd /dir/to/copy && tar cf - . ) | ( cd /where/to/ && tar xf - ) % Finding installed PCI devices Want to know which all PCI devices are installed on your box and are picked up by the kernel ? Depending upon verbosity of reply needed, do: #lspci, 'lspci -v' or 'lspci -v -v'. % Synchronising time with net time servers To synchronise the time on your system with Time Servers on the net (e.g. time.nuri.net, time.hmt.org): rdate -s some.time.server;/usr/sbin/setclock % X hotkeys Ctrl+Alt+Backspace kill X server Shift+Ctrl+Numlock Toggle numpad mouse move keys Ctrl+Alt+KeypadPlus next X mode (resolution usually) Ctrl+Alt+KeypadMinus previous X mode (resolution usually) See http://www.pixelbeat.org/lkdb/ % Changing boot parameters using GRUB At the grub boot menu press "e" and edit the boot parameters For example append "single" to boot in single user mode. Then boot the entry using "b" [boot] % Pushing process into background To temporarily stop a running process, press Ctrl-z. And then to push it in the background (so that it keeps running) type 'bg'. To get it back to foreground later, type 'fg'. You can test with this command `cat /dev/null` % Wondering how to make a safe password ? Use mkpasswd. The following will produce a unique 8 letter password with minimum 2 digits and 3 letters in upper case: mkpasswd -l 8 -d 2 -C 3 % Tracking your reboots To know the history of your last few re-boot sequences: last reboot last looks back in the wtmp file for all logins. The pseudo user "reboot" also logs in at all reboots of the system % Redraw/Clear text console If your console application is messed up (with wall messages for e.g.) a Ctrl-L will cause a redraw. % Changing priority of a process The nice value (-20 to 19) represents the priority of a process. The lower the value, the higher the priority (not as nice to others). For non interactive processes (especially on multi-user systems) do: nice low_priority_command You can retroactively give a process less priority like: renice 19 -p low_priority_pid For e.g. this is useful at the start of long running shell scripts: renice 19 -p $$ > /dev/null Only root can give processes more priority. % To take screen shots of a linux virtual console, do: setterm -dump -file screen.dump % USB storage devices USB mass storage devices are mounted as virtual scsi devices. Usually it can be mounted like: mount /dev/sda1 /mount/point If you have other scsi devices look in /proc/scsi to see which scsi device to use. You may find devlabel useful for helping with device consistency. Have a look at http://www.laks.com/ for a nice USB storage watch. % video encoder in mplayer A little known feature of mplayer (www.mplayerhq.hu) is that it contains a movie-file encoder, 'mencoder'. Try divx enco- ding with 'libavcodec' that comes bundled with it; to shrink larger 'mpeg' files to half-sized 'avi' files. % Testing/ stepping through your shell script $ sh -x script.sh 2> script.log Your script runs a bit slower but, every line that is executed (after variable expansion) gets logged. View the log later with any pager or editor. % Genesis of (weird) unix names awk This pattern scanning and text processing language was named after its authors: Al Aho, Peter Weinberger, Brian Kernighan. grep "Global Regular Expression Print" g/re/p is the ed command to print all lines matching a certain pattern (where "re" is a "regular expression"). rc (as in ".bashrc" ...) "rc" derives from "runcom", from the MIT CTSS system,ca. 1965. There was a facility that would execute a bunch of commands stored in a file; it was called "runcom" for "run commands", and the file began to be called "a runcom" % Free opensource books online http://www.pixelbeat.org/links.html % Benchmarking your HTTP server The standard Apache distribution has a built-in benchmark tool for webservers called ApacheBench (/usr/bin/ab) ... It can simulate 100s of simultaneous requests to same page; Try: ab -n 10000 -c 100 http://localhost:[port]/index.html % Text-to-pdf To convert any text file or *nix command output into pdf use a tiny utility called mpage (http://www.mesa.nl/pub/mpage) which converts any text file to postscript. The 'ps2pdf' script of ghostscript can be used for doing the pdf conversion. Try: $ man -t ls | mpage -X"ls man page" -m50l -1 | ps2pdf - ls.pdf $ cat fname.txt | mpage -X"Title" -1 | ps2pdf - fname.pdf % Sending winpopup message from linux To send a winpopup message to windows machines through SAMBA: echo "message" | smbclient -M netbiosname Note M$ are disabling the messenger service by default as of windows XP service pack 2 % Mounting an ISO image directly With a single command, you can mount an ISO file directly off the hard drive, as if it were a CD. Try : mount -o loop filename.iso /mnt/cdrom % Midnight Commander (mc) remote filesystems access remote files using ssh cd /#sh:user@machine/ access remote files using ftp cd /#ftp:user:pass@isp/public_html % Useful mozilla/firefox commands (type in URL bar): about:config low level config editor about:about show about items available view-source: view page source Note the view-source: command can be a link from a web page but it requires an absolute URL as an argument. Therefore relative links need to be transformed using javascript for e.g. % If you are transitioning from windows and would like vim or gvim to behave more like windows editors then the following is useful :source $VIMRUNTIME/mswin.vim You can also get even more like windows editors by using evim which starts in insert mode (use Ctrl+L to get to Normal Mode). % #list internet services on a system netstat -lp --inet #list active connections to/from system netstat --inet % New Linux networking commands ifconfig, route, mii-tool etc. are out of date The new kids on the block are ip and ethtool. ip link show #list interfaces ethtool interface #list interface status ip link set dev eth0 name home #rename eth0 to home ip addr add 1.2.3.4/24 brd + dev eth0 #add ip and mask(255.255.255.0) ip link set dev interface up #bring interface up (or down) ip route add default via 1.2.3.254 #set default route to 1.2.3.254 % Exporting filesystems over NFS To export filesystem in NFS with read-only access and no root write access, edit the /etc/exports file and add the following line: /dir/to/export (ro,insecure,all_squash). 'man 5 exports' for other details The `exportfs -r` command makes the /etc/exports command take affect % A common requirement in shell scripts is to print numbers with thousands seperators. You can use glibc functionality to do this like: (notice the ') printf "%'d\n" 1234 % On an rpm distribution, you can list packages by size like: rpm -qa --queryformat "%10{SIZE}\t%{NAME}\n" | sort -k1,1n The equivalent for debian is: dpkg-query -W --showformat='${Installed-Size;10}\t${Package}\n' | sort -k1,1n % Redirection cmd >/dev/null 2>&1 #redirect stdout & stderr to /dev/null cmd 2>&1 >/dev/null #redirect stdout to /dev/null & stderr out cmd >file2 file 2>&1 #all stdout & stderr in shell (script) to file % rsync really is worth knowing. Here are two common uses. To only get differences between file on the remote and local server. For e.g. if you're having problems downloading, you can run this several times to get the file. rsync -P rsync://rsync.server.com/path/to/file file This would copy file1 to file2 at around 1 MByte/s Think of it as nice for I/O. rsync --bwlimit=1000 file1 file2 % In gnome at least, one can get a screenshot of the whole screen and current window with the PrtSc and Alt+PrtSc keys respectively. However quite often it's necessary to get screenshots in situations where these keys don't work. For these situations I find a delayed screenshot initiated from a terminal on a different virtual desktop very useful. I usually do this like: sleep 5; import -window root -quality 90 screenshot.png % Shell conditionals if [ "$str" = "1" ] || [ "$int" -eq "1" ]; then echo "str or int is 1" elif [ "$int" -lt "10" ] && [ -e "file" ]; then echo "int less than 10 and file exists" fi #man test gives details of what you can put between the [ ] % Shell loops for item in 1 2 3 4; do while read line; do echo "item=$item" echo "line=$line" done done Note you can pipe into and out of loops also but be wary as they're run in a subshell so any change in environment variables are local to the loop. % Piping Vs Redirection: > and < etc. are used for connecting files to commands | is used for connecting commands You can't just use "command | file" as this puts commands and files in the same namespace. In other words if one had a file with the same name as a command then there would be ambiguity about what to do. % Trying distributions without rebooting http://umlbuilder.sourceforge.net/walkthrough.shtml % Users su #change to root user su -l #same but get correct root $PATH etc. (login shell) su -l user #change to user su -c "cmd" #just run cmd as root and exit sudo cmd #just run cmd as root without password and exit visudo #setup sudo (as root). `man sudoers` for more info % If you don't select "System clock uses UTC" then the time will not be automatically adjusted for daylight savings etc. % Having difficulty reading the output from the diff command? Consider using tkdiff instead, for a graphical side-by-side view. You can use it like diff, i.e. tkdiff file1 file2 Also you can use vim like: vimdiff file1 file2 % There are a few handy shortcuts common to all linux window managers: lower window Middle mouse click on titlebar resize window Alt + Middle mouse drag in appropriate bit of window move window Alt + Left mouse drag anywhere in window % Note when you copy something to the clipboard or selection buffer in an X application, it's thrown away when the app is closed. (unless you use an app to manage the clipboard (like xclipboard)). % There are some handy mouse shortcuts for selecting text in X. As normal a left mouse button drag selects text but most apps also allow the right mouse button to extend the selection. I.E. you can click or drag the right button to define the extent of the selection. Also in general double clicking selects a word, while triple clicking selects a line. See http://www.pixelbeat.org/docs/xclipboard.html for more.