Shell Concept

download Shell Concept

of 40

description

concept o shell programming

Transcript of Shell Concept

PowerPoint Presentation

1OutlineWhat is shell?BasicSyntaxListsFunctionsCommand ExecutionHere DocumentsDebugRegular ExpressionFind

2Why Shell?The commercial UNIX used Korn ShellFor Linux, the Bash is the defaultWhy Shell?For routing jobs, such as system administration, without writing programsHowever, the shell script is not efficient, therefore, can be used for prototyping the ideasFor example, % ls al | more (better format of listing directory)% man bash | col b | lpr (print man page of man)3What is Shell?Shell is the interface between end user and the Linux system, similar to the commands in WindowsBash is installed as in /bin/shCheck the version% /bin/sh --version

KernelOtherprogramsX windowbashcsh4Pipe and RedirectionRedirection (< or >) % ls l > lsoutput.txt (save output to lsoutput.txt)% ps >> lsoutput.txt (append to lsoutput.txt)% more < killout.txt (use killout.txt as parameter to more)% kill -l 1234 > killouterr.txt 2 >&1 (redirect to the same file)% kill -l 1234 >/dev/null 2 >&1 (ignore std output)Pipe (|)Process are executed concurrently% ps | sort | more% ps xo comm | sort | uniq | grep v sh | more% cat mydata.txt | sort | uniq | > mydata.txt (generates an empty file !)5Shell as a LanguageWe can write a script containing many shell commandsInteractive Program:grep files with POSIX string and print it% for file in *> do> if grep l POSIX $file> then> more $filefidonePosixThere is a file with POSIX in it* is wildcard% more `grep l POSIX *`% more $(grep l POSIX *)% more l POSIX * | more6Writing a ScriptUse text editor to generate the first file#!/bin/sh# first# this file looks for the files containing POSIX# and print itfor file in *do if grep q POSIX $file then echo $file fidoneexit 0% /bin/sh first % chmod +x first %./first (make sure . is include in PATH parameter)

exit code, 0 means successful7SyntaxVariablesConditionsControlListsFunctionsShell CommandsResultDocument8VariablesVariables needed to be declared, note it is case-sensitive (e.g. foo, FOO, Foo)Add $ for storing values% salutation=Hello% echo $salutation Hello% salutation=7+5 % echo $salutation 7+5% salutation=yes dear% echo $salutation yes dear% read salutationHola!% echo $salutation Hola!

9QuotingEdit a vartest.sh file#!/bin/sh

myvar=Hi there

echo $myvarecho $myvarecho `$myvar`echo \$myvar

echo Enter some textread myvar

echo $myvar now equals $myvarexit 0Output Hi thereHi there$myvar$myvarEnter some textHello world$myvar now equals Hello world10Environment Variables$HOMEhome directory$PATHpath$PS1 (normally %)$PS2 (normally >)$$process id of the script$#number of input parameters$0name of the script file$IFSseparation character (white space)

Use env to check the value11Parameter% IFS = ` `%set foo bar bam% echo $@foo bar bam% echo $*foo bar bam% unset IFS% echo $*foo bar bamdoesnt matter IFS12Parameter%./try_var foo bar bazHelloThe program ./try_var is now runningThe second parameter was barThe first parameter was fooThe parameter list was foo bar bazThe users home directory is /home/ychuangPlease enter a new greetingHolaHolaThe script is now completeEdit file try_var#!/bin/shsalutation=Helloecho $salutationecho The program $0 is now runningecho The parameter list was $*echo The second parameter was $2echo The first parameter was $1echo The users home directory is $HOMEecho Please enter a new greetingread salutationecho $salutationecho The script is now completeexit 013Conditiontest or [ if test f fred.cthen...fiIf [ -f fred.c ]then...fiif [ -f fred.c ];then...fiexpression1 eq expression2expression1 ne expression2expression1 gt expression2expression1 ge expression2expression1 -lt expression2expression1 le expression2!expression -d fileif directory-e fileif exist-f fileif file-g fileif set-group-id-r fileif readable-s fileif size >0-u fileif set-user-id-w fileif writable-x fileif executableString1 = string2String1 != string 2-n string(if not empty string)-z string(if empty string)need space !14Control StructureSyntaxif conditionthenstatementelsestatementfi

#!/bin/shecho Is it morning? Please answer yes or noread timeofdayif [ $timeofday = yes ]; then echo Good morningelse echo Good afternoonfiexit 0

Is it morning? Please answer yes or noyesGood morning15Condition Structure#!/bin/shecho Is it morning? Please answer yes or noread timeofdayif [ $timeofday = yes ]; then echo Good morningelif [ $timeofday = no ]; then echo Good afternoonelse echo Sorry, $timeofday not recongnized. Enter yes or noexit 1fiexit 016Condition Structure#!/bin/shecho Is it morning? Please answer yes or noread timeofdayif [ $timeofday = yes ]; then echo Good morningelif [ $timeofday = no ]; then echo Good afternoonelse echo Sorry, $timeofday not recongnized. Enter yes or noexit 1fiexit 0If input enter still returns Good morning17Loop StructureSyntaxfor variabledostatementdone

#!/bin/sh

for foo in bar fud 43doecho $foodoneexit 0

barfud43

How to output as bar fud 43?Try change for foo in bar fud 43This is to have space in variable 18Loop StructureUse wildcard *

#!/bin/sh

for file in $(ls f*.sh); do lpr $filedoneexit 0

Print all f*.sh files 19Loop StructureSyntaxwhile condition dostatementdone

#!/bin/shfor foo in 1 2 3 4 5 6 7 8 9 10do echo here we go againdoneexit 0

#!/bin/shfoo = 1while [ $foo le 10 ]do echo here we go again foo = $foo(($foo+1))doneexit 0Syntax until condition dostatement done

Note: condition isReverse to whileHow to re-write previous sample?20Case StatementSyntaxcase variable in\ pattern [ | pattern ] ) statement;; pattern [ | pattern ] ) statement;; esac

#!/bin/shecho Is it morning? Please answer yes or noread timeofdaycase $timeofday in yes) echo Good Morning;; y) echo Good Morning;; no) echo Good Afternoon;; n) echo Good Afternoon;; * ) echo Sorry, answer not recongnized;;esacexit 021Case StatementA much cleaner version#!/bin/shecho Is it morning? Please answer yes or noread timeofdaycase $timeofday in yes | y | Yes | YES ) echo Good Morning;; n* | N* ) echo Good Afternoon;; * ) echo Sorry, answer not recongnized;;esacexit 0But this has a problem, if we enter never which obeys n*case and prints Good Afternoon22Case Statement#!/bin/shecho Is it morning? Please answer yes or noread timeofdaycase $timeofday in yes | y | Yes | YES ) echo Good Morning echo Up bright and early this morning ;; [nN]*) echo Good Afternoon;; *) echo Sorry, answer not recongnized echo Please answer yes of no exit 1 ;;esacexit 023ListAND (&&)statement1 && statement2 && statement3

#!/bin/shtouch file_onerm f file_two

if [ -f file_one ] && echo Hello && [-f file_two] && echo therethen echo in ifelse echo in elsefiexit 0OutputHelloin elseCheck if file exist if not then create oneRemove a file24ListOR (||)statement1 || statement2 || statement3

#!/bin/sh

rm f file_oneif [ -f file_one ] || echo Hello || echo therethen echo in ifelse echo in elsefi

exit 0OutputHelloin else25Statement BlockUse multiple statements in the same placeget_comfirm && { grep v $cdcatnum $stracks_file > $temp_file cat $temp_file > $tracks_file echo add_record_tracks}26FunctionYou can define functions for structured scripts function_name() { statements }

#!/bin/shfoo() { echo Function foo is executing}echo script startingfooecho script endedexit 0

Outputscript startingFunction foo is executingScript endedYou need to define a function before using itThe parameters $*,$@,$#,$1,$2 are replaced by local value if function is called and return to previous after function is finished27Function#!/bin/shsample_text=global variablefoo() { local sample_text=local variable echo Function foo is executing echo $sample_text}echo script startingecho $sample_textfoo

echo script endedecho $sample_text

exit 0

define localvariableOutput? Check the scope of the variables 28FunctionUse return to pass a result#!/bin/shyes_or_no() { echo Is your name $* ? while true do echo n Enter yes or no: read x case $x in y | yes ) return 0;; n | no ) return 1;; * ) echo Answer yes or no esac done}echo Original parameters are $*if yes_or_no $1then echo Hi $1, nice nameelse echo Never mindfiexit 0

Output./my_name John ChuangOriginal parameters are John ChuangIs your name John?Enter yes or no: yesHi John, nice name.29CommandExternal: use interactivelyInternal: only in scriptbreakskip loop

#!/bin/shrm rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4

for file in fred*do if [ -d $file ] ; then break; fidoneecho first directory starting fred was $filerm rf fred*exit 030Command:treats it as true#!/bin/sh

rm f fredif [ -f fred ]; then :else echo file fred did not existfi

exit 031Commandcontinue continues next iteration#!/bin/shrm rf fred*echo > fred1echo > fred2mkdir fred3echo > fred4for file in fred*do if [ -d $file ]; then echo skipping directory $file continue fi echo file is $filedonerm rf fred*exit 032Command. ./shell_script execute shell_scriptclassic_set#!/bin/shverion=classicPATH=/usr/local/old_bin:/usr/bin:/bin:.PS1=classic> latest_set#!/bin/shverion=latestPATH=/usr/local/new_bin:/usr/bin:/bin:.PS1=latest version>

% . ./classic_setclassic> echo $versionclassicClassic> . latest_set latestlatest version>33Commandechoprint string-n do not output the trailing newline-e enable interpretation of backslash escapes\0NNN the character whose ACSII code is NNN\\ backslash\a alert\b backspace\c suppress trailing newline\f form feed\n newline\r carriage return\t horizontal tab\v vertical tabTry these% echo n string to \n output

% echo e string to \n output34Commandevalevaluate the value of a parametersimilar to an extra $

% foo=10% x=foo% y=$$x% echo $y

Output is $foo

% foo=10% x=foo% eval y=$$x% echo $y

Output is 1035Commandexit nending the script0 means success1 to 255 means specific error code126 means not executable file127 means no such command128 or >128 signal

#!/bin/shif [ -f .profile ]; then exit 0fiexit 1

Or % [ -f .profile ] && exit 0 || exit 1

36Commandexportgives a value to a parameterThis is export2#!/bin/shecho $fooecho $bar

This is export1#!/bin/shfoo=The first meta-syntactic variableexport bar=The second meta-syntactic variable

export2

Output is

%export1

The second-syntactic variable%37Commandexprevaluate expressions %x=`expr $x + 1` (Assign result value expr $x+1 to x)Also can be written as%x=$(expr $x + 1)

Expr1 | expr2 (or)expr1 != expr2Expr1 & expr2 (and)expr1 + expr2Expr1 = expr2expr1 expr2Expr1 > expr2expr1 * expr2Expr1 >= expr2expr1 / expr2Expr1 < expr2expr1 % expr2 (module)Expr1