Dr. Mark Humphrys

School of Computing. Dublin City University.

Home      Blog      Teaching      Research      Contact

Online coding site: Ancient Brain

coders   JavaScript worlds


CA170      CA668      CA686

Online AI coding exercises

Project ideas

Introduction to Shell programming

Unix/Linux command-line - One-liner "programs" at the command prompt (e.g. prog piped to prog).

Shell programming - Text file of multiple Unix/Linux commands (e.g. "if" condition then execute command, else other command).

The combination of one-liner command-line plus multi-line Shell programs gives you a programmable User Interface, where you can quickly write short programs to automate repetitive tasks.

Shell program = an interpreted program (i.e. not compiled). Also known as a "Shell script" or "batch file" of UNIX commands.
Like .BAT files on Windows command line.


How to make a Shell program

  1. Put it in a directory that is in the PATH.
    In this course we will put it in $HOME/bin
  2. It can have any extension (typically no extension).
  3. Put valid UNIX commands in it.
  4. Make it executable:
     $ chmod +x file
  5. Run it by typing its name:
    $ file
    $ file &

Alternative ways of working

  1. Pass program as arg to shell:
     $ sh prog 
    Advantage: Does not have to be executable. Does not have to be in PATH.
    Disadvantage: Have to type "sh" all the time. Have to be in same directory (or else type more complicated path to program).

  2. Use file extension:
    $ prog.sh
    Advantage: Can easily see what the file is from a directory listing.
    Disadvantage: Have to type the .sh
    Could be used when no one ever types the name. (e.g. The script is only ever called by a program.)

I don't use either of these.

Arguments and returns

A Shell program is different to something typed on the command-line.
It can have arguments, and can exit at any point.

$1     1st command-line argument
$2     2nd command-line argument

$*     all arguments

#      comment 

exit		exit the Shell script
exit 0		exit with a return code that other progs can query

$?		return code of last prog executed

if, test and flow of control

# test if 1st argument = "0"

if test "$1" = "0"
 echo "yes"
 echo "no - first argument is $1"

ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.

Wikipedia: Sometimes I link to Wikipedia. I have written something In defence of Wikipedia. It is often a useful starting point but you cannot trust it. Linking to it is like linking to a Google search. A starting point, not a destination. I automatically highlight in red all links to Wikipedia and Google search and other possibly-unreliable user-generated content.