Transcript
Page 1: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell Scripting

Operētājsistēma UNIX (DatZ6007)Pasniedzēji: prof. Guntis Bārzdiņš, doc. Normunds Grūzītis

Līdzautori: Ģirts Folkmanis, Juris Krūmiņš, Kristaps Džonsons, Leo Trukšāns, Artūrs Lavrenovs

Latvijas Universitāte

Page 2: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Outline

w Shell featuresw Helper utilities: introw Connecting utilities with shell scriptingw Helper utilities: detailsw Piping, advanced examplesw Shell scripts as files, programming constructs

Page 3: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Bash

w We will talk about bash; there might be differences for other shellsn bash – GNU Bourne-Again Shelln Authors: Brian Fox and Chet Ramey (1989)

l Free Software Foundation; a replacement for the Bourne shell

w Popular (default) in different distributionsw To find your current (login) shell, type the command

echo $SHELL/bin/bash

Page 4: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell Featuresw The shell command language (sh) is defined in SUS / POSIX

n The language interpreted by the shelln The standard utility programs (150+)

w bash is rather a dialect of the POSIX shell languagen Has acquired many extensions that may change the behavior of valid

POSIX shell scriptsn Supports a --posix switch which makes it POSIX-compliantn Conforms to the POSIX standard if invoked as sh

l /bin/sh

w Few systems are fully SUS/POSIX compliantn e.g. Debian GNU/Linux, OpenBSD, NetBSD are not w.r.t. the utility section

l Many commands are missing on all systemsl Others require special installation

Page 5: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell features

w Two types of usage:n Command line – interactiven Shell script, usually non-interactive

w Shell scripts:Series of commands written in plain text fileLike batch file is MS-DOS but much more powerful

Page 6: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell features

w Two types of commands:n Internal commands – built in the shell interpreter

l e.g. type -a cd

n External commands – calling other executable filesl e.g. type -a ls

w Almost everything applies to both command line usage and shell scripts

Page 7: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

External commands

Page 8: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

External commands

w The environment variable $PATH determines where to search for external programsn $ echo $PATH/bin:/usr/bin:/usr/local/bin:/opt/bin

n “:” as a separatorn export PATH=$HOME/bin:$PATH

w The current directory “.” is usually not included in $PATHfor security reasons

Page 9: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell configuration files

Page 10: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell configuration files

Page 11: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Aliasingw Assigning a command to a shorter “alias”

n Type a shorter command instead of the longer onew Aliasing is useful for options that you want all of the time

n alias rm “rm –i”

w Aliasing is similar to shell function definitionsn dos2unix() { cat $1 | perl -pe 's/\r\n$/\n/g'; }n unix2dos() { cat $1 | perl -pe 's/\n$/\r\n/g'; }

w Both can be specified in a shell profile file

Page 12: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Internal commands

w A list of built in commands, that are handled internally without running an external commandn Does not require forking off a separate processn Needs direct access to the shell internals

w Most commonly used internal command is cd, used to change the current working directory

Page 13: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Internal commands$ helpGNU bash, version 2.05b.0(1)-release (i686-pc-linux-gnu)

These shell commands are defined internally.

Type `help name' to find out more about the function `name'.Use `info bash' to find out more about the shell in general.

A star (*) next to a name means that the command is disabled.

%[DIGITS | WORD] [&] (( expression ))

. filename :

[ arg... ] [[ expression ]]

alias [-p] [name[=value] ... ] bg [job_spec]

bind [-lpvsPVS] [-m keymap] [-f fi break [n]

builtin [shell-builtin [arg ...]] case WORD in [PATTERN]

cd [-L|-P] [dir] command [-pVv] ...

...

Page 14: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

SUS: shell grammar%token WORD%token ASSIGNMENT_WORD%token NAME%token NEWLINE%token IO_NUMBER

%token AND_IF OR_IF DSEMI/* '&&' '||' ';;' */

%token DLESS DGREAT LESSAND GREATAND LESSGREAT DLESSDASH/* '<<' '>>' '<&' '>&' '<>' '<<-' */

%token CLOBBER/* '>|' */

/* The following are the reserved words. */

%token If Then Else Elif Fi Do Done/* 'if' 'then' 'else' 'elif' 'fi' 'do' 'done' */

%token Case Esac While Until For/* 'case' 'esac' 'while' 'until' 'for' */

...

Page 15: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

SUS: shell grammarcomplete_command : list separator

| list;

list : list separator_op and_or| and_or;

and_or : pipeline| and_or AND_IF linebreak pipeline| and_or OR_IF linebreak pipeline;

pipeline : pipe_sequence| Bang pipe_sequence;

pipe_sequence : command| pipe_sequence '|' linebreak command;

command : simple_command| compound_command| compound_command redirect_list| function_definition;

compound_command : brace_group| subshell| for_clause| case_clause| if_clause| while_clause| until_clause

Page 16: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

w Various small external programsw Helpful when working with shell scripts or the

command linew Called from shell (scripts or command line)w Somehow transforms input into output, based on

the parameters

Page 17: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ cat: concatenates files and prints on stdout§ Syntax: cat [file1] [file2] … [fileN]

$ cat /etc/*release DISTRIB_ID=UbuntuDISTRIB_RELEASE=14.04DISTRIB_CODENAME=trustyDISTRIB_DESCRIPTION="Ubuntu 14.04.5 LTS"NAME="Ubuntu"VERSION="14.04.5 LTS, Trusty Tahr"ID=ubuntuID_LIKE=debianPRETTY_NAME="Ubuntu 14.04.5 LTS"VERSION_ID="14.04"

Page 18: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ echo – displays a line of text§ Besides the program /bin/echo, also usually

built in the shell (takes precedence)§ Syntax: echo [STRING]$ echo quick brown fox

quick brown fox

Can be used to display environment variables$ echo $HOME

/home/girtsf

Page 19: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ wc – prints the number of newlines, words or bytes in files§ wc [options] [file1] [file2] … [fileN]

§ By default, newlines, words and byte counts are displayed

§ Options§ -c : print only byte count§ -w : print only word count§ -l : print only line count

Page 20: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ Example use of wc:$ wc /etc/passwd50 76 2257 /etc/passwd

$ wc -l /etc/passwd50 /etc/passwd

lines words bytes

lines only

Page 21: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ grep – prints lines matching a pattern§ grep PATTERN [file1] [file2] … [fileN]

§ The lines that contain PATTERN are printed to the standard output

§ If no files are specified, input is taken from thestandard input

§ Advanced versions of grep allow using regular expressions in PATTERN

Page 22: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ File “testfile” contains the following lines:$ cat testfilethe quick brown

fox jumped overthe lazy dog

§ We search for “the”:$ grep the testfilethe quick brown

the lazy dog

Page 23: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

§ Some useful parameters for grep:§ -i : ignore case (“the” finds “the”, “The”, “THE”,…)§ -l : output filenames with matches, not the contents§ -B <n> : output also n lines before the matching line§ -A <n>: output also n lines after the matching line

§ See the man page (“man grep”) for all parameters

Page 24: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

w tee – reads from stdin and writes to stdout and filesn Syntax: tee [File1] [File2] .. [FileN]

w Example of tee taking user’s input from terminal and writing to 3 files:$ tee a b csome string^Dsome string$ cat asome string$ cat bsome string$ cat csome string

Page 25: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

w Any program can be used as a helper programw More examples later

Page 26: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Connecting utilities with shell scripting

w Standard I/O streamsw I/O redirection to/from filew I/O redirection using a pipew Command substitution

Page 27: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Standard I/O

w Every process, when run, has 3 already open data streams (file descriptors, fd):n Standard inputn Standard outputn Standard error

Page 28: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Standard I/O

w When run interactively (from command line), these streams are attached to the terminal:n Standard input attached to user’s keyboard inputn Standard output attached to user’s terminal outputn Standard error attached to user’s terminal output

w Usually referred to as stdin, stdout, stderr

Page 29: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Standard output & error

w “ls” command does not use stdin, but stdout and stderr

n Sample stdout from “ls” :$ ls -l /etc/passwd-rw-r--r-- 1 root root 2257 Oct 22 13:35 /etc/passwd

n Sample stderr from “ls” :$ ls -l /etc/asdfasdfls: /etc/asdfasdf: No such file or directory

n Both stdout and stderr simultaneously:$ ls -l /etc/passwd /etc/asdfasdfls: /etc/asdfasdf: No such file or directory

-rw-r--r-- 1 root root 2257 Oct 22 13:35 /etc/passwd

Page 30: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to/from file

w By default, the 3 streams are attached to the terminalw This can be overridden when executing a command

n “>” specifies that stdout is redirected to a filen “<“ specifies that stdin is taken from a filen “2>” specifies that stderr is redirected to a filen “&>” specifies that both stdout and stderr are redirected to

the same file

Page 31: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to/from file

w Syntax:n <cmd> [ > <file1>] [ < <file2> ] [ 2> <file3> ]

w For redirections which are specified, the respective stream will be attached to the specified filen None, one, two or all three streams can be specified

w If output file exists:n > - replace the filen >> - append to the file

Page 32: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to file

w Sample stdout redirection to a file$ ls -l /lib/ > direktorijas_saraksts$ cat direktorijas_sarakststotal 4035

-rwxr-xr-x 1 root root 7488 Oct 6 12:33 cpp

drwxr-xr-x 13 root root 1024 Oct 25 15:57 dev-statedrwxr-xr-x 2 root root 1024 Jun 28 09:53 evms

drwxr-xr-x 2 root root 2048 Aug 23 15:25 iptables

...

$

Page 33: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to file

w Sample stdout redirection to a file$ ls -l /asdf > direktorijas_sarakstsls: /asdf: No such file or directory

$ cat direktorijas_saraksts$

n The file is empty, as no output was sent to stdoutn The error message was sent to stderr which was attached to

user’s terminal

Page 34: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to file

w Sample stderr redirection to a file$ ls -l /asdfasdf 2> errlog

$ cat errlogls: /asdfasdf: No such file or directory

$

n Now, stderr was redirected to file and file containsthe error message

Page 35: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection to file

w Example of stdout, stderr redirection to file$ ls -l /asdfasdf /lib 2>errlog >dir$ cat errlogls: /asdfasdf: No such file or directory$ cat dirtotal 4035-rwxr-xr-x 1 root root 7488 Oct 6 12:33 cppdrwxr-xr-x 13 root root 1024 Oct 25 15:57 dev-statedrwxr-xr-x 2 root root 1024 Jun 28 09:53 evmsdrwxr-xr-x 2 root root 2048 Aug 23 15:25 iptables...$

Page 36: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection from file

w Sample stdin redirection from a filen First, we create file “a” with the following contentthe quick brown foxjumped over a quick brown fox

n Use wc by redirecting the standard input instead of supplying the file name as a parameter

$ wc < a2 10 50

Page 37: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection with pipes

w Task: given a file, output the total number of words in those lines, that contain substring “the”

w Example input:$ cat testfile

the quick brown

fox jumped overthe lazy dog

$

w Lines 1 and 3 match, total number of words = 6

Page 38: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection with pipes

w Solution with redirection to files:n First find the lines, save them into a temp filen Then use the wc utility to count the number of words

$ grep the testfile > tmpfile

$ wc –w < tmpfile

6

Page 39: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection with pipes

w A temp file was used to save the output of grepw The input to wc was taken from the temp file

w A better way: connect the standard output of one program to standard input of another one directlyby using a pipe

Page 40: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

I/O Redirection with pipes

w Syntax: program1 | program2 (|- the pipe symbol)w A mechanism for inter-process communication (IPC),

provided by the special filesystem pipefsn The data is handled in FIFO ordern The pipe has no name; it is created for a single use; both ends must

be (are) inherited from the same process which created the pipel No temporary files!

$ grep the testfile | wc -w6

Another example: $ ls -1 | wc –l

Page 41: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Command substitutionw By using backticks, a sub-command is executed first

n The sub-command is substituted (on the command line) by its standard outputl The output can be stored in a variable

n A backtick or backquote: `n Alternative syntax: $() – allows for nesting

w Example:usr@nix:/$ cd `echo $HOME` usr@nix:/$ H=`echo $HOME`usr@nix:~$ usr@nix:/$ cd $H

Substituted with the value of $HOME

Page 42: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

w We will examine the following utilities:n cutn sortn uniqn awkn sed

Page 43: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

cut

w cut – removes sections from each line of file(s)n Extract sections from a text-file by selecting columns

w Syntax: cut [OPTION]... [FILE]...w Options:

n -d DELIM : use DELIM instead of TAB charactern -f LIST : output only these fields (delimited by DELIM)n -c LIST : output only these characters

w See man page for more options

Page 44: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

cut

w Example: output second word on each linen Delimiter: the space charactern Field: 2

$ cat athe quick brown foxjumped over a quick brown fox$ cut -f 2 -d ' ' aquickover

w Example – extract certain fields from the passwd file:$ cut -d':' -f1,3-4 /etc/passwd --output-delimiter=$'\t'

Page 45: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sort

w sort – sorts lines of text filesn sort [OPTION]... [FILE]...

w Writes a sorted concatenation of given files to stdout

w Useful options:n -r : reversen -n : compare according to string’s numerical value

w See man page for more options

Page 46: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sort

w sort - sort text file reversed

$ cat a fishdoganimalbird

$ sort -r afishdogbirdanimal

Page 47: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sort

w Sort numeric values as text

$ cat a5412 this line should go last998 this line should go second50 this line should go first999 this line should go third

$ sort a50 this line should go first5412 this line should go last998 this line should go second999 this line should go third

Page 48: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sort

w Sort numeric values as numbers

$ cat a5412 this line should go last998 this line should go second50 this line should go first999 this line should go third

$ sort -n a50 this line should go first998 this line should go second999 this line should go third5412 this line should go last

Page 49: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

uniq

w uniq – removes duplicate lines from a filen uniq [OPTION]... [INPUT [OUTPUT]]

w Discards all but one of successive identical lines from INPUT (or stdin), writing to OUTPUT (or stdout)

w Usually used together with sort, to get file without duplicate lines

Page 50: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

uniq

wJust sorted:

$ cat a | sortbirdbirddogdogfishfishfly

wsort | uniq:

$ cat a | sort | uniqbirddogfishfly

Page 51: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

awk

w gawk (GNU awk) - pattern scanning and textprocessing languagen GNU implementation of the AWK programming languagen Conforms to the definition of the language in POSIXn This in turn is based on the description of AWK

Programming Language by Aho, Kernighan and Weinbergern Originates from 1970s

Page 52: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

awkw Complete language interpreter

n Variablesn User defined functionsn …

w Useful for small one-linersn For processing text files

l A file is treated as a sequence of records (lines by default)

w An AWK program is a series of pattern-action pairsn A record is scanned for each pattern in the program

Page 53: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

awk

Task: sum all the numbers in the file$ cat a

1

2

3

4

5

$ cat a | awk '{ sum += $1 } END { print sum }'

15

executed on every line executed at the end

first field

Page 54: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

awk

w Sum the 2nd field (separated by colons) of those lines that contain the letter “a”

$ cat azzz:1:azzz:2:bzzz:3:bzzz:4:bzzz:5:a

$ cat a | awk -F ':' '{ if(/a/) sum += $2; } END { print sum }'

6

field delimiter

Page 55: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sed

w sed – stream editor (from 1970s)w Used to perform basic text parsing and transformation

on an input stream (a file or an input from a pipeline)n While in some ways similar to an editor which permits

scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient

w Simpler than awk, smaller feature set (20+ commands)

Page 56: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sed

w Replace some substring with another$ cat a

bird barks

mouse runs

$ sed 's/barks/flies/' < a

bird flies

mouse runs

Regular expression

The substitute command

Page 57: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

sed

w Replace some characters with othersn Replacing ‘b’ with ‘B’, ‘i’ with ‘I’ etc.

$ cat a

bird barks

mouse runs

$ cat a | sed 'y/bis/BIS/'BIrd BarkS

mouSe runS

The transform command

Page 58: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Advanced example (1)

w Calculate the total bytes transferred by Apachen First, take only successful lines (containing error code 200)n Sum up byte field

w The log file format:

159.148.123.123 - - [28/Oct/2004:18:11:36 +0300] "GET /somefolder/file.php HTTP/1.1" 200 127602 "-" "Opera/7.54 (X11; Linux i686; U) [en]"

Page 59: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Advanced example (1)

$ sudo cat /var/log/apache2/access.log | grep ' 200 ' | awk '{ bytes += $10 } END { print bytes }'

1105654194

n cat file n grep for " 200 "n Sum up 10th column, output the result at the end

w Alternatively:$ sudo cut -f9-10 -d' ' /var/log/apache2/access.log | awk '{ if($1 == 200) bytes += $2 } END { print bytes }'

1105653994

Page 60: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Advanced example (2)

w Calculate the number of hits per remote host in Apache log filen Output the most active hosts first

159.148.123.123 - - [28/Oct/2004:18:11:36 +0300] "GET /somefolder/file.php HTTP/1.1" 200 127602 "-" "Opera/7.54 (X11; Linux i686; U) [en]"

Page 61: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Advanced example (2)$ cat access.log | cut -d ' ' -f 1

| sort | uniq -c | sort –n -r

w First, cut out the host part (1st field) and sort the outputw Remove the duplicate lines

n Prefix the remaining lines by the number of occurrences (frequency counts)w Sort the output again: in the reverse-frequency order

w The final output:348698 159.148.111.222123485 159.148.48.5412313 80.123.123.4... ...

Page 62: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

UNIX for Poets(by Kenneth Church)

w Uzdevums: doto teksta failu (piem., Raiņa korpusu) sadalīt vārdlietojumos; izveidot sakārtotu vārdformu biežumsarakstu

w tr 'A-ZĀČĒĢĪĶĻŅŖŠŪŽ' 'a-zāčēģīķļņŗšūž' < Rainis.txt| tr -sc 'a-zāčēģīķļņŗšūž' '\n'| sort| uniq -c| sort -n -r > Rainis_freq.txt

w 1613 un 418 tik 323 lai 204 nau524 kā 374 ar 312 vai ...462 no 362 tā 306 uz 124 sirds445 kas 361 vēl 291 to ...430 ir 359 tu 285 man 95 saule427 es 349 ko ... ...

Page 63: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Helper utilities

w Some more utilities that can be usefuln head, tail - output the first/last part of filesn basename - strip directory and suffix from filenamesn bc - an arbitrary precision calculatorn sleep – sleep specified number of secondsn tr – translate or delete charactersn true, false – always return success/error code

w Read the man pages

Page 64: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

The ABCs of Unix

w A is for awk, which runs like a snailw B is for biff, which reads all your mailw C is for cc, as hackers recallw D is for dd, the command that does allw E is for emacs, which rebinds your keysw F is for fsck, which rebuilds your treesw G is for grep, a clever detectivew H is for halt, which may seem defectivew I is for indent, which rarely amusesw J is for join, which nobody usesw K is for kill, which makes you the bossw L is for lex, which is missing from DOSw M is for more, from which less was begot

w N is for nice, which really is notw O is for od, which prints out things nicew P is for passwd, which reads in strings twicew Q is for quota, a Berkeley-type fablew R is for ranlib, for sorting a tablew S is for spell, which attempts to belittlew T is for true, which does very littlew U is for uniq, which is used after sortw V is for vi, which is hard to abortw W is for whoami, which tells you your namew X is, well, X, of dubious famew Y is for yes, which makes an impression, andw Z is for zcat, which handles compression

Page 65: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Another UNIX command reference

w Use the man pages for further details

Page 66: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Tips for working in a shell

w The UP arrow – repeats the previous command

w history – internal bash command that shows the command history

w CTRL-R and a few chars recalls last command that contains these chars:n (reverse-i-search)`re': grep text file*

w Use script to make a typescript of terminal session

w Use TAB for the built-in auto-completion

w CTRL+A – moves the cursor the start of the linen CTRL+E – moves the cursor to the end of the line

w CTRL+C – sends the kill signal (SIGINT) to the currently running (foreground) process

Page 67: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Process Manipulationw Once you run a program, that program will suspend the terminal you called

it in (the terminal will not be receiving input from you).

n You can start the program in the background to avoid this:l myprog &

n You can suspend a program that is running and send it tobackground, if you already started it:l Ctrl-Z (to suspend)l bg (sends the suspended program to the background)

w ps (show running processes)w top (monitor running processes)w kill (kill processes)

w & (send process to background)w bg (send process to background) / fg (get process from background)w Ctrl+C (terminate process)w Ctrl+Z (suspend process)

Page 68: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Shell scripts as files

w Everything that can be called from the command line can also be called from a shell script

w A shell script is a series of commands written in a plain text filen Shell is a command-line interpreter

w A shell script in UNIX is like a batch file in MS-DOS, but, in general, it is more flexible and powerful

Page 69: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Running a shell script

w As a parameter to the shell interpreterl bash some_script.sh

w Specifying the interpreter on the first linel First line: #!/bin/sh

w Can be omitted if the script consists only of a set of generic system commands, using no internal shell directives

l Make it executable: chmod a+x some_script.sh

l Execute: ./some_script.sh

Page 70: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Basics

w Interpreted line by linew The same effect when entering the lines one

by one in the interactive shell

Page 71: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Sample shell script

#!/bin/sh# comment lineecho "what a fine day: "date

w Output, when executed:what a fine day: Thu Oct 28 23:37:39 EEST 2004

Interpreter to be used

Regular commands to execute

Page 72: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Variables

w Sample “hello world” with variables:#!/bin/shSTR="Hello World!"echo $STR

w When assigning, $ is not usedw When getting the contents, use $

w No data types – string, number, character, all the samen Essentially, sh variables are character stringsn Depending on context, sh permits comparisons and arithmetic operations

Page 73: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

More variables

#!/bin/bash

DATE=`date +%Y%m%d`WHAT='/home/girtsf'

DEST="/backups/$DATE.tgz"tar cvzf $DEST $WHAT

w Results in calling:tar cvzf /backups/20041028.tgz /home/girtsf

Page 74: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Conditionals

w if TEST-COMMANDS; then CONSEQUENT-COMMANDS; fi

w If TEST-COMMAND's return status is zero,the CONSEQUENT-COMMANDS list is executed

#!/bin/bashT1="foo"T2="bar"if [ "$T1" = "$T2" ]then

echo expression evaluated as trueelse

echo expression evaluated as falsefi

Page 75: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Command line arguments

w Automatically defined variablesn $0 – contains shell script namen $1 – contains first argumentn $2 – contains second argumentn …n $* - contains all arguments as a string

Page 76: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Command line arguments

$ cat printer.sh:#!/bin/sh# A script to print a file#if cat $1thenecho -e "\n\nFile $1 found and printed"

fi

$ ./printer.sh file.txt

Returns an error code

0 = successful

If 0, executes then

Page 77: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Comparisons

w Either "test <expression>" or "[ <expression> ]"n if test $1 -gt 0 n if [ $1 -gt 0 ]

w Numeric comparisons:n -eq, -ne: equal / not equaln -lt, -le, -gt, -ge : less than, less than or equal, greater

than, greater than or equal

Page 78: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Comparisons

w String comparisonsn string1 = string2 string1 is equal to string2n string1 != string2 string1 is not equal to string2n string1 string1 is NOT NULL or not defined n -n string1 string1 is NOT NULLn -z string1 string1 is NULL (zero length)

Page 79: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

File tests

w -e file file existsw -s file file is not zero sizew -f file file is a regular file (not a directory or device)w -d file file is a directoryw -w file file has write permission for the user running the testw -r file file has read permissionw -x file file has execute permissionw -L file file is a symbolic linkw ...

Page 80: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Logical Operators

w ! expression Logical NOTw expression1 -a expression2 Logical ANDw expression1 -o expression2 Logical OR

Page 81: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Yet another example#!/bin/sh# Script to test if..elif...else#if [ $1 -gt 0 ]; thenecho "$1 is positive"

elif [ $1 -lt 0 ]thenecho "$1 is negative"

elif [ $1 -eq 0 ]thenecho "$1 is zero"

elseecho "Opps! $1 is not a number, give me a number"

fi

Page 82: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Arithmetic expansion

w Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the resultn Translating a string into a numerical expression

w The syntax for arithmetic expansion is: $((expression))A=5B=4C=$(($A*$B))echo $C

Alternatively: let C=A*B / let "C = A * B"

Page 83: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Loops: forfor { variable name } in { list }do

iterate through the items in the list and for each item repeat all statements in the do block

done

for i in 1 2 3 4 5doecho "Welcome $i times"

done

Page 84: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Loops: for

w You can use for together with file name expansion (globbing) to perform the same action for several files

#!/bin/shfor x in *txtdocat $x

done

Page 85: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Loops: for

for (( expr1; expr2; expr3 )) do

repeat while expr2 is truedone

for (( i = 0; i <= 5; i++ ))doecho "Welcome $i times"

done

Page 86: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Loops: while

while [ condition ]do

command1command2command3...

done

Page 87: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Many more features

w See man page

w Linux Shell Scripting Tutorial: A Beginner's handbook:n http://www.freeos.com/guides/lsst/

w Advanced Bash-Scripting Guiden http://www.tldp.org/LDP/abs/html/index.html

Page 88: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Word guessing game

w Source: http://www.ltn.lv/~guntis/unix/mini.txt

+------|/ | | o | O | / |

MATER_ALJuusu mineejums: i

Page 89: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Main partizveleties_vardustripas

gaj=0

while true;do

zimet_karatavas $gaj

echo $vecho -n "Juusu mineejums: "read ievgajiens $iev

if [[ $v == $vards ]]; thenuzvara; exit

fi

if [[ $gaj -eq 10 ]]; thenzaude; exit

fidone;

Page 90: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Get a random wordizveleties_vardu(){

local sk r

if [[ -e /usr/share/dict/words ]];then

echo Nemu vienu nejausu vardu no vardnicassk=`cat /usr/share/dict/words | wc -l`r=$(($RANDOM % $sk + 1))vards=`tail -n $r /usr/share/dict/words | head -n 1

| tr a-z A-Z`else

echo Vardnica nav atrasta, nemu nokluseto varduvards="KARATAVAS"

fisleep 1

}

Page 91: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Convert letters to underscores

stripas(){

local ii=${#vards} # String lengthv= # Empty stringwhile [[ $i > 0 ]];do

i=$(($i-1))v=${v}_ # Append to string

done}

Page 92: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Comparison partgajiens() {

b=${iev:0:1} # Get first charl=${#vards}i=0ir=0while [[ $i < $l ]]; do

t=${vards:$i:1} # Get char at i-th positionif [[ $t == $b ]]; then

v2=${v2}$bir=$(($ir+1))

elsev2=${v2}${v:$i:1}

fii=$(($i+1))

doneif [[ $ir -eq 0 ]]; then

gaj=$(($gaj+1))return

fiv=$v2

}

Page 93: unix shell scripting4n2 - SigmaNetguntis/unix/unix_shell_scripting.pdf · Shell Scripting OperētājsistēmaUNIX (DatZ6007) Pasniedzēji: prof. GuntisBārzdiņš, doc. Normunds Grūzītis

Perl / Python scripting

w #!/usr/bin/perlw Perl is a text- and file-manipulation language that has developed

into an all-purpose scripting languagew Incorporates the most widely used features of other powerful

languages, such as C, sed, awk, and various shells, into a singleinterpreted script language

w Gets “rid” of the common Unix philosophy of using many small tools to handle small parts of one large problem

w It's easy to write code in Perl, but hard to read it


Top Related