Shell programming

Piyush P Kurur

February 2, 2015

Basics

What is Shell

  • It is a program that accepts your commands (one line at a time)

  • Executes it.

  • A shell is a full fledged programming language.

  • Slightly strange syntax because it has to double up as a command processor.

How many shells?

  • bash: Bourn Again Shell (Default on Gnu/Linux)
  • tcsh: Default shell on BSDs
  • zsh: A powerful new shell.

My shell?

  • Check your password entry
$ grep ppk /etc/passwd
ppk:x:1000:1000:Piyush P Kurur,,,:/home/ppk:/usr/bin/zsh

Shell programming.

The classical hello world program.

$ echo "Hello world"

Redirecting and piping

  • cmd > filetowrite
  • cmd < inputfromfile
  • cmd >> appendtofile
  • cmd1 | cmd2 | cmd3
$ who | wc -l

Some filters and transformers

  • grep: search for a pattern in the file (or stdin)
  • sed : basic stream editor.

$ who | grep james | sed 's/james/007/'

Shells support

  • loops
  • conditionals
  • cases.

Variables

  • foo=bar : Careful no space after =
  • $foo : the value of the variable foo

Funny characters

$ echo *
$ echo \* ; echo 'The * is not a problem here'
$ foo=bar
$ echo "The value of foo is $foo" "$foo"-bar

Quotes

  • single quotes: protects the string from shell interpretation

  • double quotes: protects but variables are substituted

  • back quote or back tick: Run command and substitute the value.

Let us write a count down program.

for i in `seq 10 -1 0`
do
    clear
    banner $i
    sleep 1
done