1 / 70

Introduction to Shell Scripts

A script is a group of commands stored in a file The file should be executable: chmod +x myScript The 1 st line in refers to the shell ie: /bin/bash. Introduction to Shell Scripts. #!/bin/bash #File: hello.sh echo “Hello World #running a script: hello.sh. A “Hello World” Script.

rogersa
Download Presentation

Introduction to Shell Scripts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A script is a group of commands stored in a file The file should be executable: chmod +x myScript The 1st line in refers to the shell ie: /bin/bash Introduction to Shell Scripts

  2. #!/bin/bash #File: hello.sh echo “Hello World #running a script: hello.sh A “Hello World” Script

  3. #!/bin/bash #args begin at $0 and go to $9 echo $3 echo $2 echo $1 echo $0 #above $9 use the form ${nnnn} echo ${10} ${7}(We may talk about the shift cmd) Receiving Arguments

  4. The shell automatically expands the command line with files myScript file1 ~king/Y* *.c *.txt day[1-9].inf Missing arguments are assumed to be NULL Passing Arguments

  5. #!/bin/bash echo “Name of this script: “ $0 echo “Number of args: “ $# echo “All the args as a single string: $* ”#does not include $0 echo “All the args as a list of strings: $*”#does not include $0 echo “Process ID: “ $$ echo “Parent Process ID: “ $PPID echo “Exit status of the last command: $?” echo Special Variables

  6. By default, all variables are local to the script or shell in which they occur. To make a variable global – export it export PATHexport USERID=”FRED27” Environment Variables

  7. When a program or a subshell is executed, copies of all global variables are passed to the subshell. Local variables are not passed #!/bin/bash #File vegas.sh x=10 export y=11 other.sh #!/bin/bash #File other.sh echo “x is not defined: $x y is defined: $y” Unless exported, what's done in vegas.sh, stays in vegas.sh What's the Difference?

  8. PS1 This the command line prompt PS2 The command line continuation prompt PS3 Prompt for the select statement PS4 Command Trace prompt PS1=”Hello> “ PS2= “Continue...>” Hello >Enter your next command \ Continue...> continue your command (we'll cover PS3 and PS4 later) Special Environment VariablesPROMPTS

  9. There are only 2 datatypes for environment variables: string and integer. You can declare them using the typeset builtin, but its not req'd at a beginner stage. Shell variables are not strongly typed. If a value looks like an integer you can treat it like an integer or a like a string, depending on your needs. typeset -i myInteger Data Types MyInteger=12345

  10. There are 4 ways to do a calculation.* The first uses double round brackets. Any variable inside the brackets does not require a $ to dereference the value, however to use the result of an expression you need to put a $ in front of the brackets. y=3(( x = 2 * y + 7 )) z=$(( 2 * x )) echo $((++x)) *The reason is historical. In the 35+ years of Unix there have been various shells with different capabilities. The bash shell includes these for reasons of backward compatibility with its most popular predecessors. Manipulating Integers I

  11. The 2nd syntax uses the let statement let x=7 let y=++x let z=x*y let k=z+5 echo “x: $x y: $y z: $z k: $k x: 8 y: 8 z: 64 k: 69 Note: The variable on the right side does not use a $ to dereference it Manipulating Integers II

  12. You can use C's Operators

  13. The 3rd syntax, which is probably the least powerful, uses a utility known as expr. Each operator and operand is treated as an arg to the utility, and must therefore be separated with a whitespace character. Arithmetic operators are limited to: + - * / and %. Comparison operators are allowed, but <, >, ( and ) must be quoted or escape quoted so that they are not interpreted by the shell. expr 5 + $x expr 3 '<=' 2 + 7 y=`expr $x + $z` Manipulating Integers III

  14. For more difficult calculations, or for using real numbers use bc (basic calculator) and a here file. The result returned to the shell is treated as a string, not a number! x=`bc <<EOF 5+2^.5+ $yEOF` Here the ^ is used for exponentiation and takes the square root of the number. bc is more powerful in that it handles both integers and reals, temporary variables and extended precision arithmetic (hundreds of digits long. More Complicated Calulations

  15. Assignment is easy:x=Hello y=”Hello World” z=$xConcatenation is also easy: echo $x$y echo $x” George, “$y Manipulating Strings (I)

  16. In any environment you need to: Copy a string x1=$x2 Concatenate strings x1=$x2$x3 Retrieve a substring x2=${x1:2:5} get the length of a string echo ${#x1} String Operators

  17. Bash has 3 other interesting features 1. The expr utility can handle strings including the ability to find the position of a string in a substring 2. The :- := and :? operators can be used to assign default values or actions to strings if they are undefined 3. A subset of regular expression pattern matching and substitution can be achieved using the %, #, %% and ## operators For more info, see the Advanced Bash Reference by Meyer Cooper (posted on my web site) Manipulating Strings II

  18. Double Quotes: allows quoting of whitepaces “Hello $USER” Single Quotes – Prevents expansion of metacharacters 'Hello $125.00' Back Quote – evaluates the commands inside list=`who | cut -c1-8` BackSlash – quotes a single character or a hex or octal value \t The 4 types of quote

  19. read line read value1 value2 value3 read a b c < myFile The values read in are from stdin. Each value read in is separated by a whitespace character on the input line and is assigned to the next variable in the list - except for the last variable – its value is the whole rest of the line. Input – the read cmd

  20. read -p “Enter a value: “ myValue read -s -p “S means silent. Passwd?” pass read -d. -p “Multiline input. End with . “ sentence read -t 3 -p “3 seconds to self destruct... ” xxx read -n 1 -p “Enter a single character response: “ read options

  21. Here's one that's new to me. You can use triple < to send a variable to a command as if it were a file or a 1 line “here” file.x=”The rain in Spain” wc <<< $x 1 4 18 this is the same as:echo $x | wc Special BASH feature: <<<

  22. Most Unix commands send output to stdout and stderr (ie: the screen) Sometimes we want to hide this, either by redirecting to a file or /dev/nullcat -n myFile ls -l > dirList cat Feb March 2>/dev/null Output

  23. If we've redirected stdout and stderr, we can still direct output to the screen by directing output to /dev/tty echo “My Message” > /dev/tty Secret Slide

  24. The echo command is for printing text and the value of variables echo “Hello World: $USER”echo -n “-n suppresses a new line echo

  25. printf fmt value1 value2 value3 .. printf uses many of the same format codes used by c: types: %x %o %d %f %lf %e %g %smodifiers: + - 0 # * width and precision: ie: %12.5lf printf

  26. #!/bin/bash #File: add.sh #Description: Prompts and adds two numbers read -p “Enter 1st number: “ number1 read -p “Enter a 2nd number: “ number2 result=`bc <<EOF $number1 + $number2 EOF` echo "The sum is: $result" echo "Using expr: `expr $number1 + $number2`" Simple Program – Add 2 Numbers

  27. Linux dialog box functions for use in scripts: dialog presents a text only version. kdialog only works in X-Windows and presents a gui gdialog will present a graphic version in X, but will downgrade to text only if X is not detected (Class discussion: merits and other alternatives) Adding Dialog Boxes

  28. kdialog --yesno “Should we continue” 2>/dev/nullecho $?kdialog --password "Enter password " 10 50 2>/dev/null dialog --title Greeting - - infobox “Hello World” 3 20 gdialog --title "My List" --checklist "Items" 10 30 3 \ a Steak on b Strawberries off c Milk off \ d Rutabage off f Aspirin on \ g Icecream on Some examples

  29. Status codes can be found in $?. 0 means success, 1 means No, 2 means cancel dialog sends output to stderr, kdialog and gdialog sent output to stdout dialog is text only and currently has the most features. gdialog automatically uses the X gui when available, but create a text box if not. kdialog currently has more types of dialogs than gdialog but less than dialog. It also generates some (non-important) error codes which must be discarded into /dev/null. Results from dialogs

  30. Here's a trick when trying out commands: PS1='`echo “$0> “`' The status of the last command will appear in the command prompt Secret Slide v

  31. A shell script can do many of the things a C program can do – and if it can't we can write a utility in C or another language to do it. Shell scripts are interpreted and slowBut they are quick to write and can easily glue different commands together. (Why is that?)

  32. while [ condition ] do cmd1 ... cmd2 ... ... done do and done are treated as if the are separate statements. Either they appear on separate lines or with a semicolon: while [condition]; do; stmt; stmt; done while loops

  33. until [ condition ] do cmd1 ... cmd 2 ... ... done until [ condition ] is identical to while [ ! condition ] until loops

  34. #Loop until EOF (or read fails) while read line do echo “Value input: “ $line usleep 40000 done Sample while loop

  35. for x in 1 2 4 9 25 36 49 do echo The value of x is $x done for x in “$@” do echo cmd line argument $i is $x (( i += 1 )) done Note: for x in “$*” only iterates once for x in list

  36. for variable in hello 75 good-bye -1 do echo $variable done names=”Joe Helen Kris Sam” for name in $names do echo $name done More examples: for x in a list

  37. for ((i=0; i<10;i++)) do printf “%4d \n\n“ $i done Counting with for

  38. if condition then cmd1 ... cmd2 ... fi If Statement

  39. if grep -sq Merlin Yankee.txt then echo We found Merlin in the text fi The grep command acts as a condition -s silence. Suppress error messages -q quiet. Suppress found text What's left? $? - whether or not grep succeeds if example

  40. if condition then #do something #for several lines elif condtion2 then #do something else else #until we find the keyword fi fi then, elif and else must appear as separate statements, much like do and done The if statement

  41. Any Unix command, C program or Shell Script can be used as a condition if cd ~/public/html then echo “I've switched to public_html” else echo “Error code: $?” echo “You are missing a public_html directory” fi Conditions

  42. Of course, if we find an error we should try to fix it if `cd ~/public_html` then echo “I've switched to public_html” elif `gdialog --title “Assistance” --yesno “Missing public_html - create?” 5 20` then mkdir ~/public_html else echo “Sorry - can't continue....” exit 1 fi Conditions

  43. if [ -e “$1” ] then echo “File $1 exists” else echo File $1 does not exist fi We test a condition by using [ ]. Using a single set of [ ] will also work. Leave spaces around each operator. Conditions with files

  44. Other File Conditions

  45. if [ $f1 -ot $f2 ] then echo file $f1 is older than $f2 fi if [ $f1 -nt $f2 ] ;then echo file $f1 is newer than $f2 fi Comparing Two Files

  46. if [ $f1 -ef $f2 ]; then echo $f1 and $f2 are the same file echo The inode value is the same echo They reside on the same file system fi if [ Other File Comparisons

  47. if [[ $i -le 10 ]] #i is <= 10 then echo $i is small fi Other operators: -eq -ne -lt -gt -ge Numeric Conditions

  48. && Short Circuit and || Short Circuit or grep Merlin Yankee.txt && grep bucket jargon.txt (who | grep smith) || echo Smith not logged on(gcc x.c -o x && x ) || vim x.c Combining Multiple Conditions

  49. echo -n “Chose a, b or c” read choice case $choice in a) echo You chose a ;; b) echo You chose b ;; [cC]) echo you chose c ;; *) echo you chose none of the above echo “Try again?” esac #yeah, case spelled backwards Note: Choice is matched against a shell regular expression. case

  50. PS3=”Select an Entree (1-2) select name in "Red Fish""Blue Fish" do case $name in "Red Fish") echo You chose Snapper break ;; "Blue Fish") echo You chose Tuna break ;; *) echo Try again sleep 2 clear esac done echo A fine choice sir $name $REPLY select

More Related