Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Eng. Software Lab

Similar presentations


Presentation on theme: "Computer Eng. Software Lab"— Presentation transcript:

1 Computer Eng. Software Lab
242/ , Semester 1, Bash Scripting Please ask questions Use the bash shell to write scripts (small programs) that can make Linux more powerful and easier to use.

2 1. Create and Run a Shell Script
code make executable run

3 2. Predefined Variables Name Meaning % echo $HOME HOME
The C Shell 2. Predefined Variables Name Meaning HOME The full pathname of your home directory PATH A List of directories to search for commands MAIL The full pathname of your mailbox USER Your user id SHELL The full pathname of your login shell TERM The type of your terminal PWD Current work directory EDITOR Default editor DISPLAY GUI location % echo $HOME Copyright Department of Computer Science, Northern Illinois University, 2005

4 (String) Variables How to use: varname=value // create
echo $varname // print read varname // read in a value e.g: % name=andrew % echo "My name is: $name" % read foo % echo $foo

5 Script with Variables use these two code run

6 Numeric variables let varname=value Simple arithmetic: let count=1
let count=$count+20 let count+=1

7 Arithmetic Expressions
Another way to do maths is by using $((expression)): % echo $((123+20))

8 Arithmetic in Scripts code run

9 Variables commands To delete both local and environment variables
unset varname To prohibit change readonly varname list all environment variables: printenv list all shell variables set

10 Read Options -p prompt // read after printing promt
-n nchars // only read nchar characters -s // no echo (good for passwords) -t timeout // only wait for this time For more details, see

11 Example

12 Special Characters Chars written as $'string' are special: \a bell
\b backspace many more… \xHH char for the hexadecimal value HH \uHHHH Unicode char for the hexadecimal value HHHH

13 Examples I pressed the "uparrow" key "leftarrow" key -e to print
"extended" chars or use $'…' I heard nothing 

14 3. Command Substitution Used to substitute the output of a command in place of the command itself Two forms: $(command) // use this one `command` // backquote; hard on a Thai keyboard Examples: % echo "User $(whoami) is on $(hostname)" User ad is on fivedots % echo "Today is" `date` Today is Fri Jul 13 13:58:

15 4. if-else and elif written as test expression
if [ expression ] then statements fi else if [ expression ] then statements elif [ expression ] else fi Put spaces around [ and ] [ expression ] can also be written as test expression

16 5. Types of Expression An expression can involve: String comparisons
Numeric comparisons File operators Logical operators

17 String Comparisons Examples:
[ s1 = s2 ] (true if s1 same as s2, else false) [ s1 != s2 ] (true if s1 not same as s2, else false) [ s1 ] (true if s1 is not empty, else false) [ -n s1 ] (true if s1 length > 0, else false) [ -z s2 ] (true if s2 length == 0, else false s1 and s2 are variables holding strings

18 Example When comparing strings, put the variables
in quotes; it is safer. Don’t forget spaces.

19 Number Comparisons Examples:
[ n1 -eq n2 ] (true if n1 == n2, else false) [ n1 -ge n2 ] (true if n1 >= to n2, else false) [ n1 -le n2 ] (true if n1 <= to n2, else false) [ n1 -ne n2 ] (true if n1 != n2, else false) [ n1 -gt n2 ] (true if n1 > n2, else false) [ n1 -lt n2 ] (true if n1 < n2, else false) n1 and n2 are variables holding numbers

20 Example "; then" lets you put "then" after the "]"

21 Logical Ops [ ! expr ] [ e1 –a e2 ] [ e1 ] && [ e2 ]
negate a logical expression [ e1 –a e2 ] [ e1 ] && [ e2 ] AND two logical expressions [ e1 -o e2 ] [ e1 ] || [ e2 ] OR two logical expressions

22 Example

23 File Operations Examples:
[ -d fnm ] (true if fnm is a dir, else false) [ -f fnm ] (true if fnm is a file, else false) [ -e fnm ] (true if fnm exists, else false) [ -r fnm ] (true if fnm has read permission) [ -w fnm ] (true if fnm has write permission) [ -x fnm ] (true if fnm has execute permission)

24 Example return result; by default it is 0 to mean okay

25 Expressions that are not []s
[ expr ] is a short form for test expr, which evaluates expr, and returns true (0) or false (1) $? holds the exit result of the last command executed

26 A condition can use the return result of any command, not just test:
no [ ] since command is not using test

27 6. Script Arguments Variable $N is assigned the Nth argument passed to a script from the command line. Special vars: $# the number of arguments $0 the name and path of the script $* all arguments stored in 1 string all arguments stored in 1 array/list

28 Examples

29 Use $(…) to execute the command(s)

30 Rot13 I typed this.

31 7. Case Statement Use instead of if when there are many conditions:
case $var in val1) statements ;; val2) *) esac The val part can use wildcard pattern matching.

32 Two Times of Day

33 Can use | (or) and * (any text)

34 Menu Using a Case

35 Usage I typed "d", <enter> I typed "x", <enter> I typed
"q", <enter>

36 Using the Arrow Keys I pressed the "uparrow" key "leftarrow" key
"a" <enter>

37 8. Two kinds of for Loop for var in list do statements done
for (( EXPR1 ; EXPR2 ; EXPR3 )) do statements done

38 Three for-in Examples You can also write for num in {1..5}

39 -s " " puts a space between each number
error-checking seq <num> generates a sequence 1 to <num>, one number per line, -s " " puts a space between each number

40 Most output from commands
can be treated as a list, each value separated by white space.

41 Using Arrays with Loops
Create an array in two ways: pets[0]=dog pets[1]=cat pets[2]=fish or pets=(dog cat fish) To get a value, use ${pets[i]} To get all the values, use ${pets[*]} To get the size of the array, use

42 Use an array with a for-in loop:
for p in ${pets[*]} do ... done

43 A C-style for Loop in C: for (int i=0; i<n; i++)

44 9. The while Loop while expression do statements done while expression; do

45 Examples Not very secret and not very random. How to fix?

46

47 Get a random word? sort –R <file> sorts the lines in file into a random order. words is my copy of /use/share/dict/words

48 Or choose randomly from an array:
I'm printing the word to show it works.

49 10. Debugging Modify the first line of the script, #!/bin/bash, to include debugging options: -x : display each line with any variables replaced by their values before execution (use this one) -v : display each line before execution -xv : switch on both

50 Usage #!/bin/bash -x #game2.sh Debugging output starts with a "+"

51 11. Loops with a Break As in C, break causes the loop to finish.

52 12. until do statements when expression is TRUE do statements when
while expression do statements done until expression do statements done do statements when expression is TRUE do statements when expression is FALSE

53 Wait for a Login grep output is
discarded, but it still returns 0 (if success) and 1 (if no match) "-e" switches on special characters See:

54 Two Ways to Use I ran visit.sh in one window (as a background
process), and killed it from another window. I logged into fivedots with putty twice.

55 13. Functions A function with no inputs, no return result:
the function the main part of the script; what is executed first

56 A function with one input and returns 0 (true) or 1 (false).
Pass it the second command line arg., and use its result in the if-test

57 Usage

58 Functions cannot be Empty
empty () { } stillEmpty() # Comment 1 notEmpty() { : }

59 Functions can be Recursive
But you may have to define variables as local, so each call to the function as its own variables. return <number> can only return a single byte (e.g. a value between 0 and 255).

60 Factorial This means that a new n variable will be created
in each new call to fact() call from main

61 14. Script Calling Script useMenu.sh get back call the exit with
result call with 1 arg. menuExit.sh

62 Usage Test of menuExit.sh on its own Test of useMenu.sh
calling menuExit.sh

63 15. Bash Startup & Shutdown Files
/etc/profile ~/.bash_profile ~/.bash_login ~/.profile /etc/bash.bashrc ~/.bashrc ~/.bash_logout executed on login executed when a "non-login" shell is created (e.g. when an XTERM window is created when you are running Linux as your computer's OS)

64 Extending bash You can create your own bash functions and aliases which are automatically added to the built-in bash functions (e.g. added to pwd, ls). You must put these functions in your .bashrc You may also have to add code to .bashrc_profile to call .bashrc

65 Where are .bashrc and .bash_profile?
See them with ls –a in your home directory:

66 Call .bashrc from .bash_profile
# add this to your .bash_profile # if not already there if [ -f ~/.bashrc ] then . ~/.bashrc fi

67 Aliases Create a new name (alias) for a one-line command.
In my .bashrc:

68 Functions in .bashrc They are the same as functions in bash scripts.
In my .bashrc:

69 16 Text-based UI (TUI) dialog is a single command with a variety of arguments and options that allows you to display various types of graphical boxes: e.g. Yes/No boxes, input boxes, menu selections, and many more e.g. dialog --title 'Message' --msgbox 'Hello, world!'

70 Supported Dialog Boxes
calendar, checklist, dselect, editbox, form, fselect, gauge, infobox, inputbox, inputmenu, menu, mixedform, mixedgauge, msgbox, passwordbox, passwordform, pause, progressbox, radiolist, tailbox, tailboxbg, textbox, timebox, yesno

71 How a Dialog Works The dialog command generally returns when the user has made some sort of input. The input can be found either from the exit status ($?), or through the standard error stream (2>).

72 Example allows a command to be spread over multiple lines
#!/bin/bash # questions.sh # Ask some questions and collect the answers dialog --title "Questionnaire" \ --msgbox "Welcome to my simple survey" 9 18 dialog --title "Confirm" \ --yesno "Are you willing to take part?" 9 18 if [ $? != 0 ] then dialog --infobox "Thank you anyway" 5 20 sleep 1 dialog --clear clear exit 0 fi read the exit value of the last command continued

73 redirect stderr to a file, then read it in
dialog --title "Questionnaire" \ --inputbox "Please enter your name" 9 30 \ 2> _1.txt Q_NAME=$(cat _1.txt) dialog --menu "$Q_NAME, what music do you like best?" \ 1 "Classical" \ 2 "Jazz" \ 3 "Country" \ 4 "Other" \ Q_MUSIC=$(cat _1.txt) redirect stderr to a file, then read it in continued

74 if [ "$Q_MUSIC" = "1" ] then dialog --title "Likes Classical" \ --msgbox "Good choice!" else dialog --title "Doesn't like Classical" \ --msgbox "Shame" fi sleep 1 dialog --clear clear echo "Name: $Q_NAME" echo "Music type: $Q_MUSIC"

75 Problems dialog uses the ncurses library, which uses extended characters in the utf-8 character set ASCII isn't good enough If you are using putty (as I am) to connect to fivedots/takasila, then you need to set UTF-8 in its Translation settings should already be set to that

76 If your Linux is set up to support Thai, then you could instead try:
If you get ugly dialog box borders, then add these two lines to your .bashrc, and login again: export NCURSES_NO_UTF8_ACS=1 export LANG=en_US.utf8 If your Linux is set up to support Thai, then you could instead try: export LANG=th_TH.utf8

77 More dialog Info Online documentation and examples:
man dialog or dialog –h Online documentation and examples: manpage/dialog.html dialog-figures.html Articles about dialog: linux-dialog-utility-short-tutorial.html

78 17. More Information "The Linux Command Line", William Shotts
free 544 page book from Great tutorials:

79 Bash Examples/libraries
bash-shell-scripting-libraries/


Download ppt "Computer Eng. Software Lab"

Similar presentations


Ads by Google