Shell Programming Flashcards
Sequential Logic
to execute commands in the order in which they appear
Decision Logic
to execute commands only if a certain condition is satisfied
Looping Logic
to repeat a series of commands for given number of times
Case Logic
to replace “if then/else if/else” statements when making numerous comparisons
Positional Parameters
special variables used when shell scrit or shell function is called with argument parameters
$#
number of input parameters
$0
Name of the script
$1, $2, $3, …. , $9
first, second, third, and 9th argument parameter
$@
List of input parameters
$*
List of input parameters as space separated string
shift
shifts the positional parameters by one towards the beginning and drops $1 from the list. After a shift, $2 becomes $1 and so on (note if more than 9 arguments, they cannoted be directly accessed by $1 to $9 . Must use shift command
Example of Positional Variables
cat myinputs.sh #!/bin/sh echo Total number of inputs: $# echo First input: $1 echo Second input: $2
$ chmod u+x myinputs.sh $ ./myinputs.sh ONE TWO BUCKLE MY SHOE Total number of inputs: 5 First input: ONE Second input: TWO
Decision Logic: Conditional
if test-command then execute command elif test-command then execute this and execute this command else execute default command fi
What is a TEST command?
testis a built in bash commands. that returns true (0) ir false (non-zero) for a given set of arguments
Arguments structure for TEST
Argument structure is:
test item1 comparator item2
or
test option item1
• Instead of calling test, can use square brackets:
[ item1 comparator item2 ]
[ option item1 ]
you must have spaces around the brackets
test Options for File Inquiry
[ -d filename ] Test if filename is a directory
[ -f filename ] Test if filename is not a directory
[ -s filename ] Test if filename has non zero length
[ -r filename ] Test if filename is readable
[ -w filename ] Test if filename is writable
[ -x filename ] Test if filename is executable
[ -o filename ] Test if filename is owned by the user
[ -e filename ] Test if filename exists
[ -z filename ] Test if filename has zero length
All these conditions return exit status code ($?) of true (0) if satisfied and false (1) otherwise
[ -d filename ]
Test if filename is a directory
[ -f filename ]
Test if filename is not a directory
[ -s filename ]
Test if filename has non zero length
[ -r filename ]
Test if filename is readable
[ -w filename ]
Test if filename is writable
[ -x filename ]
Test if filename is executable
syntax for Combining Tests
&& represents AND
|| represents OR
Syntax: if cond1 && cond2 || cond3 … An alternative form is to use a compound statement in test using –a and –o keywords. For example: if [ cond1 –a cond2 –o cond3 … ] where cond1, cond2, cond3 are either commands returning a value or test conditions of the form: test arg1 op arg2 or [ arg1 op arg2 ]
Looping Logic
A loop is a block of code that is repeated a number of times. Either:
– A pre-determined number of times determined by a list of items
in the loop count ( for loops), or
– Until a particular condition is satisfied ( while and until
loops)
To provide flexibility to the loop constructs there are also
two statements for control:
– continue : skips to the next item in a for loop
– break : exits out of a loop
for Each Loops
for arg in list_args do command1 command2 command3 done
where the value of variable arg is set to the values provided in
list_args one at a time and the block of statements is
executed. This is repeated until the list is exhausted.
Iterating through for loops
Common programming practice to iterate through index
for (int index = 0; index <= 10; index++)...
In bash script, we can use sequence expression
{istart..iend[..incr]} where [..incr] is an
optional step size
for index in {1..10}; do…
In terms of output to terminal:
$ ls -l > flist.txt; grep -e “-rwxrw—-“ flist.txt
is equivalent to
$ ls -l | grep -e “-rwxrw—-“
Instead of a program writing data to a file on disk and the next reading it, keep information in a buffer and pass it along
Difference in resulting file system and speed!
1. First command creates a file (flist.txt) in the local directory
2. Writing to/reading from a file is slow compared to accessing
memory
man ls > ls.txt; wc < ls.txt
Standard IO redirect to (disk)
- ‘man ls’ is sent to stdout buffer
- then the buffer put the command to ‘ls.txt’ which is on the DISK
- then the txt file (DISK) is put into the stdin buffer
- The ‘wc’ command is then executed on the stdin buffer
- finally outputs to the stdout bufffer
man ls | wc
piping
- man ls is put into stdout buffer memory
- stdout buffer moves to stdin buffer
- ‘wc’ executes on the information coming from stdin buffer
- wc takes its output to the stdout buffer and is done.
Disk is never accessed, all data is accessed through buffer
grep -e
-e option is to exclude
chmod can be set with :
incremental permission change (+) or (-)
chmod ug+x myscript.sh
chmod 0-rwx myscript.sh
setting permission with “=”
perform multiple setting with “,”
$ grep -i “juliet” shakespeare.txt > names.log
$ grep -i “romeo” shakespeare.txt»_space; names.log
$ sort < names.log > names_sort.log
$ uniq < names_sort.log > names_uniq.log
$ wc –l < names_uniq.log
grep -i : case insensitive option, “juliet” and create names.log and second line just appends to the names.log for “romeo”
sort will put all the output in order by line
uniq will delete duplicate any lines where romeo and juliet are in the same line and leaving only 1 instance isntead of 2
uniq will delete any two lines that are the same next to each other.
wc -l : prints out to
«_space;HERE or <
will direct input (terminal or script) to stdin
2> &1
redirect stderr to stdout
& means “same place as”
Examples: string1='15L Fina Review!!' string2="Good luck on finals!!" var2='$string1' var3="$string2"
echo var2
echo $var2
echo $var3
Output:
var2
$string1
Good luck on finals!!
line1: without the quotes it literally echos
line2:
Example:
var1=7
var2=expr $var1 + 7
var3=expr $var1+7
var4=”expr $var1 + 7”
echo $var2
echo $var3
echo $var4
var3=
Output:
12
5+7
expr 5 + 7
line1: runs the expression and command in actually adding it. You do need spaces for EXPR cmd
line2: doesn’t uses spaces so it just prints out the string
line3: it doesn’t know to treat expr as a command since its using “ “ instead of ` `
Example:
var1=7
var3=$[$var1+8]
var5=$(($var1 + 7))
echo $var3
echo $var5
Output:
15
14
bracketts are for older syntax, but (( )) is more associated with expr
when brackets don’t need spaces
when (( )) NEED spaces since its interpreted like ` `
echo is sueful when trying to debug scripts
echo [options] stringtoprint
using “ “ is weakly quotes
using ‘ ‘ is strongly quoted
In weakly quoted strings, references to variables are replaced y the value of those variables before the output
common options
- e : expand \ special characters
- n : do not output a new-line at the end
”” : will dereference the variable and give the value
’ ‘ : will be taken literally nothing is treated as special
` ` : enclosed string is treated as a command and shell attempts to execute it, if successful the primary output from command replaces the string