8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign...

36
8 Shell Programming Mauro Jaskelioff

Transcript of 8 Shell Programming Mauro Jaskelioff. Introduction Environment variables –How to use and assign...

8 Shell Programming

Mauro Jaskelioff

Introduction• Environment variables

– How to use and assign them– Your PATH variable

• Introduction to shell programming– Permissions and making your file

executable– Input to and Output from shell scripts– Control structures

• If then else• For loops

– Booleans - test– Controlling input from within the shell

Environment Variables

• Environment variables are pieces of information used by the shell and by other programs

• Useful for customising your working environment and for shell programming

• Some examples:– PATH - the directories the system searches

to execute commands– TERM - The type of terminal (most

commonly xterm and vt100)– HOME - Your home directory– PS1 – The format of the prompt

Using Environment Variables

• Conventionally written using all capitals• To use, precede by a $ symbol• E.g. to find the value of a variable

– echo $VAR

[zlizmj@unnc-cslinux ~]$ echo $HOME/home/domain/zlizmj

• Variables are expanded by the shell before the command is executed

Using Environment Variables

• Environment variables can be used by any program

public class EnvDemo1 {

public static void main(String args[]) {

String s = System.getenv(“PATH"); System.out.println(s);

} }

Assigning Environment Variables at the Prompt

• VAR=value• The change is only visible in the current

shell• Child processes don’t automatically inherit

the environment variables from their parent.

• We use export to let child processes get the changed value.export VAR=value

• To add something to your PATH:export PATH=$PATH:new stuff

Your PATH Variable• Your PATH tells UNIX where to look for

executables• You will have a PATH already set up by

default.– You can alter it or add to it

• When you type the name of a program, the shell will look for it in your PATH.

• Each directory on your PATH should be separated by a colon

• If you change your PATH in one window it is changed only in that window (since PATH is just an environment variable)

UNIX Command Line• In UNIX you type commands at the keyboard

and the system responds• Every operating system has some sort of

command interface• In UNIX this is a separate program. There are

different versions of this program to suit the taste of the user.

• We use bash (Bourne again shell)– … but it is possible to program in other shells and

use your existing shell to interpret it

• In this lecture you will learn about Bourne shell scripting (sh), a predecessor of bash.

What is a Shell Script?

• The shell is a command interpreter– It reads commands and then executes them

• It can work interactively or from a text file• A shell program is simply a text file which

contains commands you would normally type at the prompt

• The only difference is that the commands are executed in a sub-shell (a child process is created).

Common Shell Script Components

• The first line (for bourne shell) is usually

#!/bin/sh

• # is also used for comments• Hence, this line is a special kind of

comment: it tells the shell which program to use to execute the commands in the file

Writing and Running a Shell Script

• Create the text file (using Emacs)• Make it executable (optional):

chmod u+x filename• Run it:

– filename - only works if file is executable and your PATH is set correctly!

– /Path/to/executable/filename if filename is executable. ./myscript.sh

– sh filename if you haven’t made it executable– . filename or source filename if you want to

execute it without creating a sub-shell

Making your File Executable

• ls -l tells you if files are readable, writable and/or executable and by whom

• You can change these permissions by using chmod

[zlizmj@unnc-cslinux ~]$ ls -l Foo-rw-r--r-- 1 zlizmj Domain U 0 Mar 12 10:23 Foo[zlizmj@unnc-cslinux ~]$

chmod who?what filename

Chmod Revisited

• who is one of u (user), g (group) or o (other)– can also have a (all)

• ? is one of + (add a permission) or - (remove a permission)

• what is one of r (read permission), w (write permission) or x (execute permission)

Examples of chmod

• chmod o-r coursework– prevents others from reading your file

• chmod u+x shellscript– makes the file executable by you alone

• chmod a+x directory– makes the directory accessible by everyone (a

= all user, group and others)

• chmod +x directory – We can omit the a (it’s the default)

A Simple Shell Script

Each command appears on a separate line

#!/bin/sh

ls echo "done "

#This is a comment

The Simple Shell Script in Action

[zlizmj@unnc-cslinux 1]$ lsdone.sh[zlizmj@unnc-cslinux 1]$ chmod +x done.sh[zlizmj@unnc-cslinux 1]$ ./done.shdone.shdone[zlizmj@unnc-cslinux 1]$

Input and Output

• The first argument to a shell script is called $1

• The second argument to a shell script is called $2

• ….etc…• Shell uses echo like Java’s println

Input and Output: An Example

[zlizmj@unnc-cslinux 1]$ cat firstarg.sh#!/bin/sh

#Print first argumentecho $1[zlizmj@unnc-cslinux 1]$ ./firstarg.sh hello worldhello

Control Structures

• Control structures are built in syntax for controlling the order in which execution happens

• Common structures are conditionals (if-then-else) and loops (for loops)

• Keywords should appear at the start of a line

Conditionals

• NOTE: the else is optional…

if….

then….

else….

fi

Example Using Conditionals

#!/bin/sh

if javac $1then echo "compilation done"else echo "compilation failed"fi

Booleans

• if needs something true or false• Often this means you want to

compare things• This is more complicated in shell

than in most languages• Need to use test• if test $1 -ge $2

– succeeds if the first argument is “greater than or equal to the second”

Some test inputs

• if test $1 = $2 – if $1 is equal to $2 (for strings)

• if test $1 -eq $2 – if $1 is equal to $2 (for numbers)

• -ge – (greater or equal)

• -gt – (greater)

• if test -f $FILE – if $FILE exists and is a normal file

More test inputs

• You don’t have to use “test”– if [$1 -ge $2]Is just syntactic sugar for– if test $1 -ge $2

• To learn more about test:man test

For Loops

• NOTE: There are more complex forms of loop in Bash.

for IDEN in listdo….done

A Simple For Loop• Generally this script will look in the

current directory:

• If you want it to look elsewhere, you need to put in the full path

#!/usr/bin/sh# This is list_shell.sh

for IDEN in *.shdo echo "$IDEN"done

The For Loop in Action

$ ./list_shell.shdone.shecho_three.shedit_shell.shlist_shell.shnew.shsimple.sh

Your .bash_profile is a shell script

# set up personal bin directories

PATH=$HOME/bin:$PATH:EDITOR=emacsexport PATH EDITOR

Variables and Shell

• You can use environment variables in shell scripts just like you can at the command line. – Environment variables are typically written

in upper case and are accessed using a dollar symbol

• You might also want to use other variables in shell scripts– These are typically written in lower case and

are accessed using a dollar symbol

Interacting with the User

• To get input use read followed by a variable

$ ./interact.shplease type:hello computerhello computer

#!/bin/sh# This is interact.sh

echo "please type:"read ANSecho $ANS

Variables and read

• read can have more than one argument– e.g. read COMMAND ARGUMENTS

• It will bind the first word of input to the first variable and bind the rest to the second

• This acts like a list or array – so can be used with for

More Complex read Example

#!/bin/sh# This is interact2.sh

echo "please type:"read COMMAND ARGUMENTSfor ARG in $ARGUMENTSdo $COMMAND $ARGdone

The Example in Action

$ ./interact2.shplease type:cat interact.sh simple.sh#!/bin/shecho "please type:"read ANSecho $ANS#!/bin/shecho $1

Controlling Input from Within the Shell

• << tells a command to use input from within a shell script

• Syntax is command << end where end is some string which will tell the command to stop taking input (<< EOF is most common)

• This is useful when testing programs – you can automatically run them on sample input

Example of Input Control

$ ./interact3.shplease type:hellogoodbyehello

#!/bin/sh# This is interact3.sh

./interact2.sh <<EOFecho hello goodbye helloEOF

Summary

• Environment Variables• Running Shell Programs• Command Line Arguments• If-then-else and for loops.• Controlling Input and Output.