Linux - Module 9: Basic Scripting

Tests the loop condition each time while [ ! –f /tmp/foo ]; do try_to_make_foo # makes /tmp/foo on success sleep 1 # wait 1 sec done Used when the number of loops is unknown or changes each loop

pptx18 trang | Chia sẻ: nguyenlam99 | Lượt xem: 955 | Lượt tải: 0download
Bạn đang xem nội dung tài liệu Linux - Module 9: Basic Scripting, để tải tài liệu về máy bạn click vào nút DOWNLOAD ở trên
Module 9 Basic ScriptingExam Objective 3.3 Turning Commands into a ScriptObjective SummaryBasic Text EditingBasic Shell ScriptingText EditorsA script is a sequence of commandsIf you can type it on the command line, it can be scriptedYou can branch based on tests and loop over collectionsThis is all available from the command line, tooScripts are repeatable and consistent and free you to do more interesting workEditorsScripts are text filesLibreOffice will add formatting, making it unusablenano and vi / vim are popular editorsOf the two, nano is far easier to usenanoType as normal, use arrow keys to move aroundMost commands are Control + another characterContext sensitive commands are at the bottom of the screen, e.g. ^X to exit, ^W to find^G gets you help anywhereshebang#!#! is the shebang (hash + bang)Tells the kernel what shell interpreter to use to run the scriptMust be on the first line#!/bin/sh#!/usr/bin/rubyLets you run the script with ./script no matter which shell the user hasWorking with VariablesVariablesTemporary storage of data in memoryAssigning (no $):FOO=“hello”CWD=`pwd`BAR=“Hello $NAME”Using (need a $):$FOOecho “Hello $NAME”Special Variables$1..$9 are the arguments to the script./test.sh hello there # $1=“hello” $2=“there”$? is the exit code of the last command to be runuse “exit 1” to exit your own script with error code 1Working with ConditionalsConditionalsif something; then do thisfiif something; then do thiselif something else; then do thatelse try thisfi# something returns an exit code. If it is 0, then “do this” will be executed up until fi# alternative syntax, allows for multiple tests and a default option if you wantteststest –f /tmp/foo # test if file existstest ! –f /tmp/foo # test if file doesn’t existtest $A –eq 1 # is $A = 1 (numeric)test “$B” = “Hello” # string comparisontest $A –lt 10 # $A < 10?alternatively, [ is the same as test:if test –f /tmp/foo; then # it worksif [ -f /tmp/foo ]; then # looks much nicer!Casecase ”$GREETING" inhello|hi) echo "hello yourself" ;;goodbye) echo "nice to have met you" echo "I hope to see you again" ;;*) echo "I didn't understand that"esacLoopsThe for loopOperates over a fixed set of items or a globNAMES=“Alice Bob Charlie”for N in $NAMES; do echo “Hello $N”donefor FILE in *; do ls –l $FILEdoneWhile loopsTests the loop condition each timewhile [ ! –f /tmp/foo ]; do try_to_make_foo # makes /tmp/foo on success sleep 1 # wait 1 secdoneUsed when the number of loops is unknown or changes each loop

Các file đính kèm theo tài liệu này:

  • pptxle_module_09_566.pptx