Summary Bash Shell Programming

BASH SHELL CODING

Bash Shell control :

o   Gets aliases from .bashrc

o   Create alias as : alias gothere="whatever you want your alias to do"

 

Shell commands

Command

Meaning

;

Jump to the next line to process

|

Standard input to the next command is whatever came out of the prior command

( )

Process whatever is in parentheses as a sub-command

<

What follows is the input

>>

Append to the following output file

>

Create the following output file (and overwrite it if it exists)

2>>

Append error output to the following file

2>

Create the following error file

&

Send the process into the background

*

Display the name of every file in the working directory and below

.*

Display the name of every file above the working directory and . files in the working directory

$

Get the value at the variable name  (or parenthesized expression)

?

Match a single unknown character in a search, 

[  ]

Match an character from the set, ranges such as 0-9 or A-Z work

` .. `

Make whatever is inside the quotes execute as a sub program

=

Assign right side to variable named by left side – no spaces surrounding = allowed; No $ on variable name on the left side. If you use variables on the right side, put $

&&

Run the right side only if the left side is successful

||

Run the right side only if the left side failed

((  ))

Treat what is inside as numbers

:

Null (needs spaces around it) – often used in if statement if nothing should be done.

#

comment

 

To make a metacharacter just a normal character:

·         Put a backslash in front of the character

·         Put double quotes around  it (but that does not make  $ \  or ` inactive)

·         Put single quotes around it (and that removes all processing)

Processes:

·         See them with ps

·         Kill them with kill -9 <pid>

Commands to list files and directories:

List files in current dir:

·         find . -maxdepth 1 -type f

·         ls -p | grep -v / | column

List subdirectories:

·         ls –d *

 Echo a line with return at the end:

·         echo –n   (echo –e “ \n” also works)

Environment variables:

·         Examples: $HOME, $PATH

·         Set alone shows all environment variables

·         Set environment variable values: PATH=”/.:$PATH”

·         /dev/null – null devices. You can redirect output to it to avoid all output

How to make a shell script:

·         Write commands that would work on the command level, but write them inside a file.

o   You may use the parameters to the shell as $1 - $9.

o   $0 is the name of your script

o   $# is the number of variables actually passed into your script

o   $* and @* list all parameters passed into your script

o   “$*” lists all parameters in one string

o   $? – last exit status (result of last command – 0 good and 1 bad)

o   Use shift to move the parameter list one to the left

o   Good practice to start with #!/bin/bash

o   Use exit(any number 0 – 255) to send a number back to caller – 0 is success

·         Change the permissions of that file to be executable (chmod u+x filename)

·         Run the shell by typing ./filename and a string of parameters space separated.

·         Debug/Trace with bash –x filename

Child processes:

·         Running a script creates a child process

·         Running a script with the dot command        . scriptname    will run inside the parent process

·         Interrupts such as ctrl c is passed to the child process

·         Export variable name (without the $) will export the variable to new child processes (ex: export name)

Variables

·         Create by var=value without spaces or $. OR read var var (again no $)  or var=$(some command)

·         Get value of variable using $

Read command:

·         Places everything until the next line into a shell variable, defaulting to the variable REPLY.

·         Every word after read is considered a variable and created if needed.

·         Read parses at the space unless told otherwise (by environment variable IFS)

·         Reads from stdin  unless directed with < or |

·         -a means read into an array variable with variable name following –a

·         -p means write this prompt first, before taking in input

·         Example:  read name1 name2 < test1.txt

Numbers:

·         declare –i the variable value will always be treated as an integer

·         Example: declare –i  num

·         ((    )) insides will be treated as numbers. (no character can be next to parentheses)

·         Leading 0 in a number makes it be interpreted as octal so 017 represents the decimal # 15

·         Leading 0x in a number makes it be interpreted as hex.

·         Leading <Base># in a number makes it be interpreted as that base.

Conditions:

o   Test or [  ]

o    [ is a command, so must have a space next to it

o   Example: [  string1 = string2  ]

o   = , !=

o   Integer comparison: -eq, -ne, -gt, -ge, -lt, -le

o   File tests: -nt file is newer than; -ot file is older than; -ef file has the same inode number (same file)

o   Use –a for both true and –o for either true

o   Some unary tests:

o   [ -z  string ] : true if string is zero length

o   [ -n string ] : true if string is more than zero length

o   [ -p filename ] : true if file is a named pipe

o   [ -O filename ] : file exists and you own it

o   [ -r filename ] : file is readable

o   [ -S filename ] : file is a socket

o   [ -t fd ] : file descriptor is opened on a terminal

o   [ -w filename ] : file is writeable

o   [ -x filename ] : file is executable

o   [ -d filename ] : name is a directory

o   [ -f filename ] : regular file existence and not a directory

o   [ -L filename ] : file is a symbolic link

 

o    [[ ]] gives some pattern matching

o   [[ $name == [Tt]om ]] matches if $name contains Tom or tom

o   [[ $name == [^t]om ]] matches if $name contains any character but t followed by om

o   [[ $name == ?o* ]] matches if $name contains any character followed by o and then whatever number of characters after that.

o   Just shell patterns, not regex

o    

IF

·         0 is true and 1 is false for a script (reverse of normal)

·         Syntax:

o   if command

o   then

§  Command(s)

o   elif command

o   then

§  Command(s)

o   else

§  Command(s)

o   Fi

·         then” must follow the elif and if, but not else.

·         Use : if nothing should be done inside an if section.  (spaces surrounding : are important.)

CASE:

·         If/elif/else construct

·         Syntax:

o   case variable

§  value1 )

·         commands

·         ;;

§  value2 )

·         commands

·         ;;

§  )  #default

·         Commands

·         ;;

o   esac

LOOPS

·         do /done are like curly braces.

·         After done, put redirected input or output just for this loop : ex done < myfile

·         Use break to exit

·         Use continue to go immediately back to the top of the loop.

·         FOR – runs through a list (does not increment a counter)

o   Syntax:

§  for varname in list

§  do

§  your repeating commands

§  done

·         WHILE – do while the command is successful

o   Syntax:

o   while command

o   do

§  command(s)

o   done

·         UNTIL – do while the command is unsuccessful (otherwise same as while)

·         SELECT – creates menus that don’t stop until you break out of the loop

o   Syntax:

§  PS3=”Whatever you want your prompt to be for the menu “

§  select var in options list (and use ‘ ‘ to surround 2 word options)

§  do

§     Command(s)

§  done

o   Ex: select program in `ls –F` pwd date ‘some other option’ exit

Create a function:

o   Define function before use

o   Define function using: functionname() {    }

o   Call function using: functionname parm1 parm2 …

o   Function accesses parameters to it as $1, $2 ..

o   Send back information with return statement

Trap an interrupt:

o   Define the action that will happen when the interrupt occurs using: trap ‘the action to do when the interrupt occurs ‘ the signal:

o   trap 'rm -f /tmp/my_tmp_file_$$' INT

o   When the signal arrives, that command will execute, and then it will continue with whatever statement it was processing.

o   You can use a function instead of just one command. 

Guide to scripts that illustrate shell programming:

        wget http://home.adelphi.edu/~pe16132/csc271/note/scripts/______