Department of Engineering

IT Services

Some useful shell and Unix commands

To become fluent writing shell scripts you need to know about common shell commands (as shown earlier) but you also need to be aware of some common unix commands.

Shell commands

See the ksh or sh-posix man page for more info on these. In bash you can use the help command.

alias :-
to list aliases
let :-
to do maths. Eg:- let x=2*4-5 ; echo $x
set :-
to list the current variables and their values.
typeset -f :-
to list functions
typeset -i :-
to list integer variables
which :-
to find where a program is (in some shells you use whence instead)

Unix accessories

See the corresponding man page for more info on these. Note that many of the commands have dozens of options that might save you needing to write code.

This counts words lines and characters. To count the number of files in a directory, try ls | wc -l

`grep Kwan /etc/passwd' prints all lines in /etc/passwd that include `Kwan'. The return value indicates whether any such lines have been found.

a stream editor. Doing ls | sed s/a/o/g will produce a listing where all the 'a' characters become 'o'. Numerous tricks and tutorials are available from the Handy one-liners for SED file.

Strips the directory and (optionally) suffix from a filename.
Translates one set of characters to another set. For example, try
  echo "date" | tr d l
The following does case conversion
  echo LaTeX | tr '[:upper:]' '[:lower:]'
You can also use it as follows, ``capturing" the output in a variable
  new=$(echo $old | tr '[:upper:]' '[:lower:]')
This program can be used to check the existence of a file and its permissions, or to compare numbers and strings. Note that ` if [ -f data3 ]' is equivalent to ` if test -f data3'; both check for a file's existence, but the [...] construction is faster - it's a builtin. Note that you need spaces around the square brackets. Some examples,
if [ $LOGNAME = tpl ] # Did the user log in as tpl? 
if [ $num -eq 6 ]     # Is the value of num 6?
if [ $(hostname) = tw000 ] # Does hostname produce `tw000'?
                           # i.e. is that the machine name?

`ls -l | sort -nr +4' lists files sorted according to what's in column 4 of ls -l's output (their size, usually).

Extracts characters or fields from lines. cut -f1 -d':' < /etc/passwd prints all the uid's in the passwd file. The following code shows a way to extract parts of a filename.

b=$(basename $filename)
prefix=$(echo $b | cut -d. -f 1)
suffix=$(echo $b | cut -d. -f 2)

finds files in and below directories according to their name, age, size, etc.