代写代考 CMPSC 311 – Introduction to Systems Programming

CMPSC 311 – Introduction to Systems Programming
Shell Programming
Professor Suman Saha
(Slides are mostly by Professor Patrick McDaniel and Professor Abutalib Aghayev)

Copyright By PowCoder代写 加微信 powcoder

CMPSC 311 – Introduction to Systems Programming

Shell programming
• aka “shell scripting,” “Bash scripting”
• What is it?
• Series of commands
• Programming with programs
• What for
• Automating
• System administration
• Prototyping
CMPSC 311 – Introduction to Systems Programming

A sample script: shello
• First line: interpreter • The #! is important!
• Comment: # to end-of-line
• Give the file execute permission chmod +x shello
• Not determined by file extension
• Typical: .sh or none
• Runit ./shello
#! /bin/bash
# Greetings!
echo Shello world # Use a variable
echo Shello “$USER”
# Set a variable
greetz=Shellutations echo “$greetz world”
CMPSC 311 – Introduction to Systems Programming

Shell variables
• Setting/unsetting
• export var=value
• No spaces!
• unset var
• Using the value • $var
• Untyped by default
• Behave like strings
• (See help declare for more)
CMPSC 311 – Introduction to Systems Programming

Special variables
• Change shell behavior or give you information
• PWD:currentdirectory
• USER:nameofthecurrentuser
• HOME:thecurrentuser’shomedirectory
• Can usually be abbreviated as a tilde (~)
• PATH:wheretosearchforexecutables
• PS1:Bashprompt(willseelater)
CMPSC 311 – Introduction to Systems Programming

• Make a directory ~/bin
• Move shello script there
• Prepend the directory to your $PATH • PATH=~/bin:$PATH
• Change to home dir
• Run by typing shello
CMPSC 311 – Introduction to Systems Programming

Shell initialization
• Set custom variables
• At startup, bash runs shell commands from ~/.bashrc
• Just a shell script
• This script can do whatever you want
CMPSC 311 – Introduction to Systems Programming

Fun with prompts
• Main prompt:$PS1
• Special values
• \u: username
• \h: hostname
• \w: working dir
• \e: escape (for colors)
• many others
• This is something you can set in your .bashrc
Very detailed treatment: http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/
CMPSC 311 – Introduction to Systems Programming

Special characters
echo Penn State is #1 echo Micro$oft Windows echo Steins;Gate
• Whathappened?
• Manyspecialcharacters • Whitespace
• #$*&^?!~’`”\{}[]<>()|;
• Whatifwewantthesecharacters?
CMPSC 311 – Introduction to Systems Programming

• Removes specialness
• Hard quotes:’…’
• Quote everything except closing ‘
• Soft quotes:”…”
• Allow variables (and some other things)
• Good practice:”$var”
• Backslash (escaping)
• Quotes next character
CMPSC 311 – Introduction to Systems Programming

• In C: argc and argv[]
• Split at whitespace
• How can we override this?
• Arguments to a script
• ./script foo bar
• $# is the same as argc
• all args
• “$1” to “$9”: individual
CMPSC 311 – Introduction to Systems Programming

Debug mode
• Shows each command
• Variables expanded
• Arguments quoted
• Run with bash -x
• Temporary – just for that run
• bash -x shello
• Use -xv for even more info
CMPSC 311 – Introduction to Systems Programming

• Make a script that:
• Prints its first argument doubled
./script1 foo foofoo
• Prints its first four args in brackets, one per line
./script2 “foo bar” baz [foo bar]
CMPSC 311 – Introduction to Systems Programming

Redirecting input/output
• Assigns stdin and/or stdout to a file • echohello>world
• echohello>>world
• trhj
int main(int argc, char **argv) {
// Quick-and-dirty int conversion
return atoi(argv[1]); }
CMPSC 311 – Introduction to Systems Programming

Custom prompt for today
• You can include $? in your prompt • Now try:
./status 42
CMPSC 311 – Introduction to Systems Programming

Exit status in scripts
• $?: get exit status of the previous command
• The exit status of a script comes from the last command it runs
‣ Or use the exit builtin to exit early, e.g. exit 1
• ! cmd reverses the value: 0 for failure and 1 for success ‣ Exactly like the ! (“logical not”) operator in C
CMPSC 311 – Introduction to Systems Programming

Conditionals
• Exit status is used as the test for if statements:
if list; then cmds
• Runs list, and if the exit status is 0, then cmds is executed
• Therearealsoelifandelse commands that work the same way.
CMPSC 311 – Introduction to Systems Programming

Test commands
• Builtin commands that test handy conditions • true: always succeeds
• false: always fails
• Many other conditions: test builtin ‣ Returns 0 if test is true, 1 otherwise ‣ Full list:help test
CMPSC 311 – Introduction to Systems Programming

What do these do?
$ test -e status.c $ test -e asdf
$ test -d status.c $ test -d /etc
$ test 10 -gt 5 $ test 10 -lt 10 $ test 10 -le 10 $ test 12 -ge 15
CMPSC 311 – Introduction to Systems Programming

Useful tests
• test -e file ‣ True if file exists
• test -d dir
‣ True if dir exists and is a directory
• test -z “$var”
‣ True if var is empty (zero-length)
• test -n “$var”
‣ True if var is nonempty
• test str1 = str2
• test num1 -gt num2
‣ or-lt,-ge,-le,-eq,-ne
CMPSC 311 – Introduction to Systems Programming

Shorthand tests
• Shorthand test:[[ … ]] ‣ Workalike for test
• For example:
test $age -ge 16 &&
echo can drive
[[ $age -ge 16 ]] &&
echo can drive
• Now say age=3 and try again
CMPSC 311 – Introduction to Systems Programming

Command lists
• Simple command list:;
‣ Runs each command regardless of exit status ‣ Example:
do_this; do_that
• Shortcutting command lists ‣ && stops after failure
‣ || stops after success
‣ Examples:
foo && echo success bar || echo failed
CMPSC 311 – Introduction to Systems Programming

Try it out
true && echo one
true || echo two
false && echo three false || echo four
test -e Makefile && make cat dog || echo bird ./status 4 && echo 4 ./status 0 && echo 0 cat dog; cat status.c touch status.c; make make clean && make
CMPSC 311 – Introduction to Systems Programming

Conditional loops
• Youcanwriteawhileloopusing the same idea:
while list; do cmds
• Runslist,cmds,list,cmds,list…foras long as list succeeds (exit status 0)
• Similarly,anuntilloopwill execute as long as list fails
CMPSC 311 – Introduction to Systems Programming

Conditional practice
if ! [[ -e foo ]]; then echo hello > foo
while [[ “$x” -lt 99999 ]]; do echo “$x”
if cat foo; echo Same
if cat dog; echo Woof
then to you
CMPSC 311 – Introduction to Systems Programming

Command substitution
• Command substitution allows the output of a command to replace the command itself
• In recent versions of bash: $(command) • More commonly: `command`
• file $(which ls) • file `which ls`
CMPSC 311 – Introduction to Systems Programming

For statement
• Theforloopis“for-each”style: for var in words; do
• The cmds are executed once for each argument in words, with var set to that argument
• foriin$(seq15);do echo $i;
• foriin{1..5};doecho$i;done
CMPSC 311 – Introduction to Systems Programming

For example…
for a in A B C hello 4; do echo “$a$a$a”
for ext in h c; do cat “hello.$ext”
CMPSC 311 – Introduction to Systems Programming

• Old name for filename wildcards ‣ (Comes from “global command”)
• * means any number of characters: echo *
• ? means any one character: echo hello.?
• Bulk rename:
for f in hello.*; do mv “$f” “$f.bak”
CMPSC 311 – Introduction to Systems Programming

Some more useful tools
• touch foo:“modify” the file foo without really changing it
• sleep t: wait for t seconds
• grep -F string: filter stdin to just lines containing string
• find . -name ‘*.c’: list all the .c files under the current directory
‣ Many other things you can search for; see man find
• file foo: determine what kind of file foo is
• wc: counts words/characters/lines from stdin
• bc: command line calculator
CMPSC 311 – Introduction to Systems Programming

Exercise time
• Print out “foo” once per second until ^C’d
• Find all the .png files in dir/
• Find all the files in dir/ which are actually PNG graphics
• Useapipeandbcto calculate the product of 199 and 42
CMPSC 311 – Introduction to Systems Programming

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com