[Loewald New Media]
All content on this site is by and copyright ©1994-2015 Tonio Loewald, unless otherwise specified. Best viewed in Chrome, Firefox, or Safari

25 Useful UNIX Commands

This list is not original; I found it here. I've posted it simply as a way of remembering it, and I can always add new stuff I find later.


Top displays the top processes on the system and periodically updates this information.

top (launches top)


The tail utility displays the contents of file or, by default, its standard input, to the standard output.

# tail /var/log/auth.log 
Aug 19 20:38:05 laptop su: username to root on /dev/ttyv0
Aug 20 00:10:38 laptop login: login on ttyv0 as username
Aug 20 00:11:30 laptop su: username to root on /dev/ttyp0
Aug 20 00:56:32 laptop su: username to root on /dev/ttyp1
Aug 20 01:31:26 laptop su: username to root on /dev/ttyv0
Aug 20 10:25:58 laptop login: login on ttyv0 as username
Aug 20 10:26:21 laptop su: username to root on /dev/ttyp0
Aug 20 13:58:06 laptop su: username to root on /dev/ttyp1
Aug 20 14:18:23 laptop su: username to root on /dev/ttyp1
Aug 20 14:27:39 laptop su: useranme to root on /dev/ttyp1


The ping utility uses the ICMP protocol's mandatory ECHO_REQUEST datagram to elicit an ICMP ECHO_RESPONSE from a host or gateway. ECHO_REQUEST datagrams ("pings") have an IP and ICMP header, followed by a "struct timeval" and then an arbitrary number of "pad" bytes used to fill out the packet.

$ ping -c 5 www.yahoo.com
PING www.yahoo-ht3.akadns.net ( 56 data bytes
64 bytes from icmp_seq=0 ttl=47 time=48.814 ms
64 bytes from icmp_seq=1 ttl=47 time=32.916 ms
64 bytes from icmp_seq=2 ttl=47 time=32.361 ms
64 bytes from icmp_seq=3 ttl=47 time=33.912 ms
64 bytes from icmp_seq=4 ttl=47 time=33.846 ms

--- www.yahoo-ht3.akadns.net ping statistics ---
5 packets transmitted, 5 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 32.361/36.370/48.814/6.249 ms


The passwd utility changes the user's local, Kerberos, or NIS password. If the user is not the super-user, passwd first prompts for the current password and will not continue unless the correct password is entered.

$ passwd
Changing local password for username
Old Password:
New Password:
Retype New Password:


The mount utility calls the nmount(2) system call to prepare and graft a special device or the remote node (rhost:path) on to the file system tree at the point node. If either special or node are not provided, the appropriate information is taken from the fstab(5) file.

# cat /etc/fstab
# Device                Mountpoint      FStype  Options         Dump    Pass#
/dev/ad4s1b             none            swap    sw              0       0
/dev/ad4s1a             /               ufs     rw              1       1
/dev/acd0               /cdrom          cd9660  ro,noauto       0       0
# mount /cdrom
# ls /cdrom
4.1             TRANS.TBL       etc
# umount /cdrom
# ls /cdrom


tar creates and manipulates streaming archive files. This implementation can extract from tar, pax, cpio, zip, jar, ar, and ISO 9660 cdrom images and can create tar, pax, cpio, ar, and shar archives.

$ tar -cf t2.tar example test three
$ ls | grep t2
$ tar -xf t2.tar
(files are now extracted)


zip is a compression and file packaging utility for Unix, VMS, MSDOS, OS/2, Windows NT, Minix, Atari and Macintosh, Amiga and Acorn RISC OS.

$ zip test.zip test
  adding: test/ (stored 0%)
$ ls | grep test
$ unzip test.zip
Archive:  test.zip


bzip2 compresses files using the Burrows-Wheeler block sorting text compression algorithm, and Huffman coding. Compression is generally considerably better than that achieved by more conventional LZ77/LZ78-based compressors, and approaches the performance of the PPM family of statistical compressors.

$ bzip2 -9 test.tar
$ ls | grep test.tar
$ bzip2 -d test.tar.bz2
$ ls | grep test.tar


The gzip program compresses and decompresses files using Lempel-Ziv cod- ing (LZ77). If no files are specified, gzip will compress from standard input, or decompress to standard output. When in compression mode, each file will be replaced with another file with the suffix, set by the -S suffix option, added, if possible. In decompression mode, each file will be checked for existence, as will the file with the suffix added.

$ gzip -9 test.tar

$ gzip -d test.tar.gz
$ ls | grep test.tar


ssh (SSH client) is a program for logging into a remote machine and for executing commands on a remote machine. It is intended to replace rlogin and rsh, and provide secure encrypted communications between two untrusted hosts over an insecure network. X11 connections and arbitrary TCP ports can also be forwarded over the secure channel.

#ssh (ip address of host)
Welcome to FreeBSD-World


The ifconfig utility is used to assign an address to a network interface and/or configure network interface parameters. The ifconfig utility must be used at boot time to define the network address of each interface present on a machine; it may also be used at a later time to redefine an interface's address or other operating parameters.

$ ifconfig (to get information about your network interfaces)


The locate program searches a database for all pathnames which match the specified pattern. The database is recomputed periodically (usually weekly or daily), and contains the pathnames of all files which are pub- licly accessible.

you may need to run /usr/libexec/locate.updatedb to update locate listing.

#locate Xorg.0.log


The kill utility sends a signal to the processes specified by the pid operands.

$ kill 694 (the id of the program to kill)


The man utility formats and displays the on-line manual pages. This version knows about the MANPATH and PAGER environment variables, so you can have your own set(s) of personal man pages and choose whatever program you like to display the formatted pages. If section is specified, man only looks in that section of the manual. You may also specify the order to search the sections for entries and which preprocessors to run on the source files via command line options or environment variables. If enabled by the system administrator, formatted man pages will also be compressed with the ``/usr/bin/gzip -c'' command to save space.

$ man find (to show information about the "find" command)


The cat utility reads files sequentially, writing them to the standard output. The file operands are processed in command-line order. If file is a single dash (`-') or absent, cat reads from the standard input. If file is a UNIX domain socket, cat connects to it and then reads it until EOF. This complements the UNIX domain binding capability available in inetd(8).

$ cat test
this is the contents of the file test


The pwd utility writes the absolute pathname of the current working directory to the standard output.

$ pwd


nano is a small, free and friendly editor which aims to replace Pico, the default editor included in the non-free Pine package. Rather than just copying Pico's look and feel, nano also implements some missing (or disabled by default) features in Pico, such as "search and replace" and "go to line and column number".

$nano test (to edit, or create and edit, the file "test")


The startx script is a front end to xinit that provides a somewhat nicer user interface for running a single session of the X Window System. It is often run with no arguments.

To use startx user most have .xinitrc file in there home directory. Examples of the file are:

$ cat ~/.xinitrc
exec fluxbox
(this will start fluxbox)
$ cat ~/.xinitrc
exec gnome-session
(this will start gnome)
$ cat ~/.xinitrc
exec startkde
(this will start kde)


For each operand that names a file of a type other than directory, ls displays its name as well as any requested, associated information. For each operand that names a file of type directory, ls displays the names of files contained within that directory, as well as any requested, associated information.

$ ls 
example test    three
$ ls -l
total 0
-rw-r--r--  1 owner  group  0 Aug 20 13:44 example
-rw-r--r--  1 owner  group  0 Aug 20 13:44 test
-rw-r--r--  1 owner  group  0 Aug 20 13:44 three


grep searches the named input FILEs (or standard input if no files are named, or the file name - is given) for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

$ ls 
example test    three
$ ls | grep th


In the first synopsis form, the cp utility copies the contents of the source_file to the target_file. In the second synopsis form, the con- tents of each named source_file is copied to the destination target_directory. The names of the files themselves are not changed. If cp detects an attempt to copy a file to itself, the copy will fail.


$ cp test test2
$ ls -l | grep test
-rw-r--r--  1 owner  group           0 Aug 20 13:40 test
-rw-r--r--  1 owner  group           0 Aug 20 13:41 test2

To copy a directory:

$ cp -r test test2


The rm utility attempts to remove the non-directory type files specified on the command line. If the permissions of the file do not permit writing, and the standard input device is a terminal, the user is prompted (on the standard error output) for confirmation.

Example (file):

$ rm test2
$ ls -l | grep test2

Example (dir):
what you get when you try to rm a dir is:

$ rm test
rm: test: is a directory

to get around this do:

$ rm -r test
$ ls -l | grep test


The mkdir utility creates the directories named as operands, in the order specified, using mode ``rwxrwxrwx'' (0777) as modified by the current umask(2).

$ mkdir test


dig (domain information groper) is a flexible tool for interrogating DNS name servers. It performs DNS lookups and displays the answers that are returned from the name server(s) that were queried. Most DNS administrators use dig to troubleshoot DNS problems because of its flexibility, ease of use and clarity of output. Other lookup tools tend to have less functionality than dig.

$ dig mail.yahoo.com

; <<>> DiG 9.4.1-P1 <<>> mail.yahoo.com
;; global options:  printcmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 9867
;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 8, ADDITIONAL: 8

;mail.yahoo.com.                        IN      A

mail.yahoo.com.         195     IN      CNAME   login.yahoo.com.
login.yahoo.com.        65      IN      CNAME   login-global.yahoo8.akadns.net.
login-global.yahoo8.akadns.net. 122 IN  CNAME   login.yahoo.akadns.net.
login.yahoo.akadns.net. 51      IN      A

akadns.net.             84671   IN      NS      zc.akadns.org.
akadns.net.             84671   IN      NS      zd.akadns.org.
akadns.net.             84671   IN      NS      eur1.akadns.net.
akadns.net.             84671   IN      NS      use3.akadns.net.
akadns.net.             84671   IN      NS      usw2.akadns.net.
akadns.net.             84671   IN      NS      asia9.akadns.net.
akadns.net.             84671   IN      NS      za.akadns.org.
akadns.net.             84671   IN      NS      zb.akadns.org.

za.akadns.org.          23366   IN      A
zb.akadns.org.          23366   IN      A
zc.akadns.org.          23366   IN      A
zd.akadns.org.          23366   IN      A
eur1.akadns.net.        17773   IN      A
use3.akadns.net.        17773   IN      A
usw2.akadns.net.        17773   IN      A
asia9.akadns.net.       17773   IN      A

;; Query time: 27 msec
;; WHEN: Mon Aug 20 13:34:17 2007
;; MSG SIZE  rcvd: 421


dns lookup

$ host mail.yahoo.com
mail.yahoo.com is an alias for login.yahoo.com.
login.yahoo.com is an alias for login-global.yahoo8.akadns.net.
login-global.yahoo8.akadns.net is an alias for login.yahoo.akadns.net.
login.yahoo.akadns.net has address

UNIX Pipes

UNIX pipes allow commands to send information to one another, output it to files, and take it from files. There are three kinds of pipe:


| sends the output from the command on its left to the command to its right.

$ ls | grep M
Weasel Project May 11 07.zip


> sends the output of the command on its left to the file named on its right (overwriting any previously existing file)

$ ls | grep M > files_containing_capital_M.txt
$ cat files_containing_capital_M.txt
Weasel Project May 11 07.zip


< sends the file to the right as input to the command on the left

$ ls | grep M > files_containing_capital_M.txt
$ grep < files_containing_capital_M.txt ov

Bourne Shell & Shell Scripts

The information below is from this excellent summary.


You can store data in variables.

$ test_var="fred"
	$ echo $test_var


Back quotes (`) allow you to assign the output of a command to a variable.

$ test_var=`ls`
	$ echo $test_var


awk lets you extract data from columnar output

ls -l | awk '{print $5}'


sed is the stream editor; among many things it allows you to perform search and replace on variables.

echo "Hello Jim" | sed -e 's/Hello/Bye/'


expr evaluates numeric expressions.

expr 5 + 7


tr replaces characters with other characters

ls | tr 'a' 'X'

for ... do ... loop

Simple for-loop.

# Execute ls and wc on each of several files
# File names listed explicitly
for filename in simple.sh variables.sh loop1.sh
	echo "Variable filename is set to $filename..."
	ls -l $filename
	wc -l $filename

Or even...

# Execute ls and wc on each of several files
# File names listed using file name wildcards
for filename in *.sh
	echo "Variable filename is set to $filename..."
	ls -l $filename
	wc -l $filename

Command Line Arguments

Shell variables are used to access the command line.

# Illustrates using command-line arguments
# Execute with
#	sh args1.sh On the Waterfront
echo "First command-line argument is: $1"
echo "Third argument is: $3"
echo "Number of arguments is: $#"
echo "The entire list of arguments is: $*"

Iterating over arguments

A safe way to iterate over all the arguments in a command line (safer than $*).

# Loop over the command-line arguments
# Execute with
#	sh args2.sh simple.sh variables.sh
for filename in "$@"
	echo "Examining file $filename"
	wc -l $filename


read allows you to read from the standard input, including allowing for interactive scripts.

# Shows how to read a line from stdin
echo "Would you like to exit this script now?"
read answer
if [ "$answer" = y ]
	echo "Exiting..."
	exit 0

Command Exit Status

If a command returns anything other than 0 it failed. You can check for errors thus:

# Use an if block to determine if a command succeeded
echo "This mkdir command fails unless you are root:"
mkdir /no_way
if [ "$?" -ne 0 ]
	# Complain and quit
	echo "Could not create directory /no_way...quitting"
	exit 1  # Set script's exit status to 1
echo "Created directory /no_way"

Case statement

Standard case statement.

# An example with the case statement
# Reads a command from the user and processes it
echo "Enter your command (who, list, or cal)"
read command
case "$command" in
		echo "Running who..."
		echo "Running ls..."
		echo "Running cal..."
		echo "Bad command, your choices are: who, list, or cal"
exit 0


Standard while statement

# Illustrates implementing a counter with a while loop
# Notice how we increment the counter with expr in backquotes
while [ $i -le 10 ]
	echo "i is $i"
	i=`expr $i + 1`


Conveniently processes command line options (vs. parameters)


# Save as getopt1.sh
# Execute as:
#	sh getopts1.sh  -h  -Pxerox  file1  file2
# and notice how the information on all the options is displayed
# The string 'P:h' says that the option -P is a complex option
# requiring an argument, and that h is a simple option not requiring
# an argument.

# Experiment with getopts command
while getopts 'P:h' OPT_LETTER
	echo "getopts has set variable OPT_LETTER to '$OPT_LETTER'"
	echo "	OPTARG is '$OPTARG'"

used_up=`expr $OPTIND - 1`

echo "Shifting away the first \$OPTIND-1 = $used_up command-line arguments"

shift $used_up

echo "Remaining command-line arguments are '$*'"


You can define functions in shell scripts.

echo_it () {
  echo "Argument 1 is $1"
  echo "Argument 2 is $2"
echo_it arg1 arg2