Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


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 is an interpreted program (not compiled, source code read at runtime).
Also known as a "Shell script" or "batch file".
(Windows command line has a similar concept of .BAT files.)

  


Your bin directory

  

How to make a Shell program

  1. Edit a file in your bin directory.
  2. It can have any extension (in this course we will normally use no extension).
  3. Put Linux 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.)



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"
then
 echo "yes"
else
 echo "no - first argument is $1"
fi



ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.