Main index

Introducing UNIX and Linux


Introduction to shells

Overview
Why do we need a shell?
Shell syntax
      Types of shell command
      Simple commands
      Pipelines
      Grouping commands
      Exit status
      List commands
Arithmetic
      Operators and functions
Making decisions
      The 'test' statement
            Operators used by 'test'
      The 'if' statement
Loops
      'For' loops
      'While' and 'until' loops
Searching for files
      Arguments to 'find'
Formatted output
      Arguments to 'printf'
Passing information to scripts
      Scripts with arguments
      Parameter expansion
Summary
Exercises

Exit status

Every time a UNIX command terminates, it returns a number, called its exit status, to the shell that caused it to run. Depending on the number, the shell can then take appropriate action. By convention, the exit status of a command is 0 if the command is successful. If a command fails, for whatever reason, a value different to 0 is returned (and this is typically 1). We can find out the exit status of the previous command executed by means of the special parameter $?. Immediately after running a command, type echo $? and the exit status of that command will be displayed. The exit status of a pipeline is the exit status of the last command in that pipeline.

As an example, create a file (testfile, say), protect it so that you cannot write to it using chmod and then try to write to it:

chmod -w testfile
cat >testfile
testfile: Permission denied.
echo $?
1

The 1 that is the value of $? indicates that the cat command failed.

Worked example

What is the exit status of
mv  ~/X  /
Solution: We would expect this command to fail. If ~/X does not exist, it will return exit status 1 for that reason. If it does exist, you should not have write permission for the root directory, and the command will fail. Anyhow, check the exit status by typing the command and then echo $?:

mv  /X  /
an error message
echo $?
1


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck