Download presentation
Presentation is loading. Please wait.
Published byMarsha Holt Modified over 9 years ago
1
Writing C-shell scripts #!/bin/csh # Author: Ken Berman # Date: 8-8-2002 # Purpose: display command and parameters echo $0 echo $argv[*]
2
Commands and Expressions Commands: –Sequence of UNIX commands, separated by ';' or on different lines –Typically returns value via stdout Expression –Logical expression similar to C language –Returns Boolean value (or integer)
3
Control structures for csh if ( expression ) simple command if ( expression ) then commands endif if ( expression ) then commands else commands endif
4
Control structures continued switch( testcase ) case pattern1 : commands breaksw case pattern2 : commands breaksw default: commands endsw
5
Control structures continued while ( expression ) commands end foreach var ( wordlist ) commands End
6
Variables String variables set name = value Integer variables @ name = value
7
Examples of variables % set name = Fred % echo name name % echo $name Fred % set name #not the same as % unset name % set colors = ( red green blue) % echo $colors[1] red
8
Variables continued % echo $colors red green blue % echo $colors[1-2] red green % echo $colors[4] Subscript out of range
9
Parameters for calling a script Parameters to a script are positional parameters $argv[1], $argv[2],… same as $1, $2,… $#argv number of arguments $argv[*] word list of all arguments $0 name of command (i.e. filename of script) $argv[0] is not defined
10
Different ways to display all parameters #!/bin/csh echo $argv[*] while ( $#argv > 0 ) echo $argv[1] shift end
11
Display parameters in reverse order set i = $#argv while ( $i ) echo $argv[$i] @ i-- end
12
Logical expressions if ($#argv == 0) echo "No arguments given" Logical expressions can be formed with == equal != not equal =~ string match !~ string nonmatch && and || or ! not Expressions have to evaluate to an integer or simple string
13
Hints for hw3 Create a shell vector variable containing usernames from first column of who (can use awk to do this). For each username use grep –c to count number of occurrences of username and apply sed to delete those usernames that occur less then n times. Use if-else control structure to check whether there are two arguments and whether flag –t has been used Use awk to output results in a table
14
Logical expressions involving files -d filenamefile is a directory -e "file exists -f "file is an ordinary file -o " user owns file -r "user has read access -w " user has write access -x"user has execute access -z"file is 0 bytes long Example: if (-e $file && -f $file ) then …
15
Finds a given command on the search path. The pathname found or a failure message is displayed. Simulates the command "which" #!/bin/csh set cmd = $1 foreach dir($path) if (-e $dir/$cmd) then echo FOUND: $dir/$cmd exit(0) endif end echo $cmd NOT on $path
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.