advertisement

Talk Unix Shell Script

50 %
50 %
advertisement
Information about Talk Unix Shell Script

Published on July 18, 2008

Author: Dr.Ravi

Source: slideshare.net

advertisement

UNIX Shell Script Dr. Tran, Van Hoai Faculty of Computer Science and Engineering HCMC Uni. of Technology [email_address]

What is a shell script? A series of OS commands for execution Stored in a text file #!/bin/sh rm -f /tmp/listing.tmp > /dev/null 2>&1 touch /tmp/listing.tmp ls -l [a-z]*.doc | sort > /tmp/listing.tmp lpr -Ppostscript_1 /tmp/listing.tmp rm -f /tmp/listing.tmp

A series of OS commands for execution

Stored in a text file

Components of a script #!/bin/sh rm -f /tmp/listing.tmp > /dev/null 2>&1 touch /tmp/listing.tmp # This is a comment ls -l [a-z]*.doc | sort > /tmp/listing.tmp lpr -Ppostscript_1 /tmp/listing.tmp rm -f /tmp/listing.tmp Shell in use (sh, bash, csh) Comment Command

How to invoke a script Correct way $ /bin/bash my_script arg_1 arg_2 Simple way $ my_script arg_1 arg_2 The first line specifying the shell must be provided in simple way

Correct way

$ /bin/bash my_script arg_1 arg_2

Simple way

$ my_script arg_1 arg_2

The first line specifying the shell must be provided in simple way

How to be helped Man pages hoai@moon:~> man bash ... hoai@moon:~> man sh ...

Man pages

hoai@moon:~> man bash

...

hoai@moon:~> man sh

...

Definitions Blank = chunk of tab or space Name = sequence of ASCII letters , digits , underscores , beginning with a letter or underscore Argument = string supplied on command-line

Blank = chunk of tab or space

Name = sequence of ASCII letters , digits , underscores , beginning with a letter or underscore

Argument = string supplied on command-line

Example (argument) (1) #!/bin/sh ############################## echo "Script name is [$0]" echo "First argument is [$1]" echo "Second argument is [$2]" echo "This process ID is [$$]" echo "This argument count is [$#]" echo "All arguments [$@]"

#!/bin/sh

##############################

echo "Script name is [$0]"

echo "First argument is [$1]"

echo "Second argument is [$2]"

echo "This process ID is [$$]"

echo "This argument count is [$#]"

echo "All arguments [$@]"

Example (argument) (2) hoai@moon:~> my_script.sh hoai 1 university Script name is [my_script.sh] First argument is [hoai] Second argument is [1] This process ID is [5401] This argument count is [3] All arguments [hoai 1 university]

hoai@moon:~> my_script.sh hoai 1 university

Script name is [my_script.sh]

First argument is [hoai]

Second argument is [1]

This process ID is [5401]

This argument count is [3]

All arguments [hoai 1 university]

Filename metacharacters Current working directory ( $PWD ) ~+ Previous working directory ( $OLDPWD ) ~- Home directory of user name ~ name Home directory of the current user ~ Match any character not enclosed as above [! abc ...] Match any one of the enclosed characters; a hyphen can specify a range (e.g., a-z, A-Z, 0–9) [ abc ...] Match any single character ? Match any string of zero or more characters *

Simple regular expressions (Korn shell) Pattern = sequence of patterns separated by “|” Match any strings that don't match pattern !( pattern ) Match exactly one instance of pattern @( pattern ) Match one or more instances of pattern +( pattern ) Match zero or more instances of pattern *( pattern ) Match zero or one instance of pattern ?( pattern )

Pattern = sequence of patterns separated by “|”

Example (metacharacters) List files having prefix new $ ls new* Cat files having prefix ch and one more letter $ cat ch? Vi files starting by letters from D to E $ vi [D-R]* Print files not *.o and core (Korn shell) $ pr !(*.o|core) | lp

List files having prefix new

$ ls new*

Cat files having prefix ch and one more letter

$ cat ch?

Vi files starting by letters from D to E

$ vi [D-R]*

Print files not *.o and core (Korn shell)

$ pr !(*.o|core) | lp

Quoting Charater following taken literally Everything taken literally '' Everything taken literally, except $ (variable substitution) ` (command substitution) “ (ending mark) ""

Everything taken literally, except

$ (variable substitution)

` (command substitution)

“ (ending mark)

Example (quoting) $ echo 'my class is "unix and tools"' My class is "unix and tools" $ echo "Well, isn't that "good" ?" Well, isn't that "good" ? $ echo "You have `ls | wc –l` files in `pwd`" You have 34 files in /home/hoai $ echo "The value of $x is $x" The value of $x is 100

$ echo 'my class is "unix and tools"'

My class is "unix and tools"

$ echo "Well, isn't that "good" ?"

Well, isn't that "good" ?

$ echo "You have `ls | wc –l` files in `pwd`"

You have 34 files in /home/hoai

$ echo "The value of $x is $x"

The value of $x is 100

Variables (1) Use var if set, otherwise, print value and exit ${ var :? value } Use value of var is set, otherwise use nothing ${ var :+ value } Use the length of var ${# var } Use the number of positional arguments ${#*} or ${#@} Use var if set, otherwise, user value and assign it to var ${ var := value } Use var if set, otherwise, use value ${ var :- value } Use value of var ${ var } Set variable to value var=value …

Variables (2) Same as # pattern . Remove longest matching ${ var ## pattern } Same as %pattern . Remove longest matching ${ var %% pattern } Use value of var after removing pattern from the right. Remove shortest matching ${ var % pattern } Use value of var after removing pattern from the left. Remove shortest matching ${ var # pattern }

Command forms OR cmd1 || cmd2 AND; cmd1, then cmd2 if (cmd succeeds) cmd1 && cmd2 POSIX shell arithmetic substitution cmd $((expression)) POSIX Command substitution (nesting is allowed) cmd1 $(cmd2) Command substitution cmd1 `cmd2` Pipe cmd1 | cmd2 NOT; change exit status ! cmd Commands as a group in a subshell ( cmd1 ; cmd2 ) Commands as a group in current shell { cmd1 ; cmd2 } Multiple commands on the same line cmd1 ; cmd2

Example (command forms) $ nroff file > file.txt & Format in the background $ cd; ls Execute sequentially $ (date; who; pwd) > logfile All output is redirected $ sort file | pr -3 | lp Sort file, page output, then print $ vi 'grep -l ifdef *.c' Edit files found by grep $ grep XX file && lp file Print file if it contains the pattern; $ grep XX file || echo "XX not found" otherwise, echo an error message

$ nroff file > file.txt &

Format in the background

$ cd; ls

Execute sequentially

$ (date; who; pwd) > logfile

All output is redirected

$ sort file | pr -3 | lp

Sort file, page output, then print

$ vi 'grep -l ifdef *.c'

Edit files found by grep

$ grep XX file && lp file

Print file if it contains the pattern;

$ grep XX file || echo "XX not found"

otherwise, echo an error message

Simple commands Create date strings date Evaluate variables eval Transform characters tr 'a' 'b' Simple arithmetic processor expr Predicate or conditional processor [( test )] Access lines in files head/tail Chop up a text by strings or characters cut Get directory name from path string dirname Get file name from path string basename Search for regular expressions grep Sort lines sort

Example (script) (1) #!/bin/bash alphabet="a b c d e" # Initialise a string count=0 # Initialise a counter for letter in $alphabet # Set up a loop control do # Begin the loop count=`expr $count + 1` # Increment the counter # Display the result echo "Letter $count is [$letter]" done

#!/bin/bash

alphabet="a b c d e" # Initialise a string

count=0 # Initialise a counter

for letter in $alphabet # Set up a loop control

do # Begin the loop

count=`expr $count + 1` # Increment the counter

# Display the result

echo "Letter $count is [$letter]"

done

Example (script) (2) alphabet="a b c d e" # Initialise a string count=0 # Initialise a counter while [ $count -lt 5 ] # Set up a loop control do # Begin the loop count=`expr $count + 1` # Increment the counter # Position of next letter position=`bc $count + $count - 1` letter=`echo "$alphabet" | cut -c$position-$position` # Get next letter # Display the result echo "Letter $count is [$letter]" done

alphabet="a b c d e" # Initialise a string

count=0 # Initialise a counter

while [ $count -lt 5 ] # Set up a loop control

do # Begin the loop

count=`expr $count + 1` # Increment the counter

# Position of next letter

position=`bc $count + $count - 1`

letter=`echo "$alphabet" | cut -c$position-$position` # Get next letter

# Display the result

echo "Letter $count is [$letter]"

done

Homeworks (1) Write a script for C compiler Objective: use gcc by default, if gcc is not availablle, find another compiler (ending with cc ) instead. Write a script to convert filenames to lowercase letters Input: a directory path string Output: all filenames in the directory in lowercase

Write a script for C compiler

Objective: use gcc by default, if gcc is not availablle, find another compiler (ending with cc ) instead.

Write a script to convert filenames to lowercase letters

Input: a directory path string

Output: all filenames in the directory in lowercase

Homeworks (2) Write a script to warn users using too much space Objective: find all users of the system (/etc/passwd, cut), check if someone uses > 1GB, mail him a warning message

Write a script to warn users using too much space

Objective: find all users of the system (/etc/passwd, cut), check if someone uses > 1GB, mail him a warning message

Conditional structure Loop structure Function File input/output Array are NEXT

Conditional structure

Loop structure

Function

File input/output

Array

Add a comment

Related pages

Shell script - Wikipedia, the free encyclopedia

A shell script is a computer program designed to be run by the Unix shell, a command-line interpreter. The various dialects of shell scripts are considered ...
Read more

Talk:Shell script - Wikipedia, the free encyclopedia

Talk:Shell script WikiProject ... This is the talk page for discussing improvements to the Shell script article. ... I think they originated in UNIX?
Read more

talk command to chat | Unix Linux Forums | Shell ...

Shell Programming and Scripting Unix shell scripting - KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and shell scripts and shell scripting languages here.
Read more

linux - how to send a mail with a message in unix script ...

New to unix and learning the talk and walk of it. I am writing a script in .ksh and have a requirement of sending a mail with a message. Currently using ...
Read more

Talk:Cron with Unix or Linux - MoodleDocs - docs.moodle.org

Talk:Cron with Unix or Linux ... Since wget is being used to run the cron.php script ... The whole cronclionly vs. shell invocation vs. "using wget" is ...
Read more

Unix & Linux Forums

Learn UNIX, UNIX commands, Linux, Operating Systems, System Administration, Programming, Shell, Shell Scripts, Solaris, Linux, HP-UX, AIX, OS X, BSD.
Read more

Unix shell - View topic - Script/Talk

Does anybody know how to eliminate the mysterious "cloaking" side effect of the 'script' command? I'd like to be able to 'talk' to someone with the 'script ...
Read more

[UNIX] Einführung in Shell-Scripte | tutorials.de - User ...

[UNIX] Einführung in Shell-Scripte. ... Ein Shell-Script ist eine Textdatei, ... Coders Talk; PHP; Java; C/C++.NET;
Read more

Writing your first script and getting ... - LinuxCommand.org

Writing your first script and getting it to work. To successfully write a shell script, you have to do three things: Write a script; Give the shell ...
Read more