+ All Categories
Home > Documents > въведение-в-bash-scripting

въведение-в-bash-scripting

Date post: 10-Apr-2018
Category:
Upload: eti
View: 278 times
Download: 4 times
Share this document with a friend

of 117

Transcript
  • 8/8/2019 --bash-scripting

    1/117

  • 8/8/2019 --bash-scripting

    2/117

    copy&paste brigante , :) :) :) , ! :).. , :) :)..

    . :) .pdf .odt ( .odt.pdf .. .pdf .txt , ' file extensions)brigante.sytes.net/upload/

    : , (phrozencrew),Inventive, cleaverhttp://bg.wikipedia.org/wiki/Bashhttp://www.linux-bg.org/cgi-bin/y/index.pl?page=article&id=advices&key=344082225

    http://brigante.sytes.net/linux.aspxhttp://brigante.sytes.net/linux.aspxmailto:[email protected]://brigante.sytes.net/upload/http://www.nediko.info/http://mytech.bg/uroci/22/?????/319/Bash+Scripting+Tutorialhttp://www.kaminata.net/bash-howto-t19345.htmlhttp://bg.wikipedia.org/wiki/Bashhttp://www.linux-bg.org/cgi-bin/y/index.pl?page=article&id=advices&key=344082225http://brigante.sytes.net/linux.aspxmailto:[email protected]://brigante.sytes.net/upload/http://www.nediko.info/http://mytech.bg/uroci/22/?????/319/Bash+Scripting+Tutorialhttp://www.kaminata.net/bash-howto-t19345.htmlhttp://bg.wikipedia.org/wiki/Bashhttp://www.linux-bg.org/cgi-bin/y/index.pl?page=article&id=advices&key=344082225
  • 8/8/2019 --bash-scripting

    3/117

    Bash Bourne Again Shell , . , UNIX Linux-, , . Bourne shell (sh), ( -). C shell (csh) ..

    , - shell ( -) . ,

    shell- root shell(root - ). , ventsi@debian:~$ ( $), root root@debian:~# ( # ).

    . /, PID ( ). , , . , .

    , *nix (, Linux, Unix , *nix) , ..

    ( , DOS).

    , , ..

    -, .

    . , :

    ls ( list ).

    . -, , ( ,

    OpenSource ). ls, / ( lsa ). man pages(- ), , , . ls -lsa ls , , , , .. man ls ( manual pages man Q).

  • 8/8/2019 --bash-scripting

    4/117

    , ( , / ), , , .

    (drwxr-xr-x, d , , ). . . .. / .

    , cd ( ).

    , .. cd .. ( )

    , /home/ventsi/Desktop/nixCommands /- , /home/ventsi/Desktop .

    , , -,:

    cd ~/Desktop/ && ls -lsah |grep nix*

    grep , / ( man grep).

    , ?

    :

    touch filename ( filename), , touchfilename.txt cat filename.txt( )

  • 8/8/2019 --bash-scripting

    5/117

    cat filename.txt , , ,

    :echo . > filename.txt

    :

    . :(: grep )

    grep , ,

    , , ., Shell-a.

    - , , .

    vi/Vim

    Vim vi , ,

    .

    ( vim -)

  • 8/8/2019 --bash-scripting

    6/117

    MidnightCommander (mc)

    , , , - .

    ( mc )

  • 8/8/2019 --bash-scripting

    7/117

    Lynx web .

    , , . , , , , , . , , hardcore, .

    ( Lynx google.bg)

    http://news.laptop.bg//linux-bourne-again-shellbash-------/

    http://news.laptop.bg/??????/linux-bourne-again-shellbash-???????-???-???-??-???????-?-???/http://news.laptop.bg/??????/linux-bourne-again-shellbash-???????-???-???-??-???????-?-???/
  • 8/8/2019 --bash-scripting

    8/117

    Bash (Bourne Again SHell) - ( ) v.01 (phrozencrew)

    , . bash , - . , , pipe-, . , , , . linux, , ,

    pipe-, . , , , . linux, , bash. , , . . :) :

    1. ( !)2. 3. , bash ()

    Linux/UNIX/Mac . . - , ! , !!!)9. test10. (I/O) 11. - IFS, [ ], [[ ]], $#, ( ), (( )) ... , 12. 13.

    . " Bash "

    bash, , . , "=" . ( ), (!). . 6. , bash , .

    :prom=MoetoMyIP=127.127.127.127quest=". Kefi6 li, a??"

    :Bash echo bash, , . ,

    - :Moeto IP e 127.127.127.127. Kefi6 li, a?? , :

    echo "$prom IP e $MyIP$quest"

  • 8/8/2019 --bash-scripting

    9/117

    , :

    echo '$prom IP e $MyIP$quest'

    , , :$prom IP e $MyIP$quest , , bash. , "\":

    echo "\$MyIP = $MyIP"

    : $MyIP = 127.127.127.127 , , , echo $MyIPto? bash, ? . Bash , , :

    echo ${MyIP}to

    :127.127.127.127to (wildcards), , bash, . .. . , ...

    Bash , $(programa), `programa`. $(programa). ? , - date. date , ,.. , , . :bash. , or: #000066;">echo $datata

    :Mon Nov 16 21:09:44 FLEST 2009 , :):

    datata=$(date +"%d.%m.%y")datata=`date +"%d.%m.%y"`

    .

    , . . . , :

    echo $den

    :( - !)11 ? :) "|". , . UNIX. :), :). Bash

  • 8/8/2019 --bash-scripting

    10/117

    , $(programa), `programa`. $(programa). ? , - date. date , , .. , , . : , . , man echo, . , echo . , ,

    -e echo. :\a - ()\c - \n - \r - ( MAC )\t -

    :$ echo "\n"n#

    $ echo -n "\n"\n

    :$ echo -e '\\n'"\c"\n

    $ echo -e "\n"# #[0-9a-zA-Z .]*' |cut -d'>' -f2#: Addax P2P 3.6.1.0

    #Internet Cyclone 1.99#twhirl 0.9.4#The Form Letter Machine 1.11.01#DOFUS 1.29#PowerDVD 9.0.2201.0

    , :1. wget HTML- wget -q -O - http://download.bg2. "|" grep , "-o" , . Perl- "-P".

    , index http://download.bg/. , :Addax P2P 3.6.1.0

    :). , "height=12" . a, "Addax P2P 3.6.1.0" - "". , , , . - [0-9a-zA-Z .]. "*" "0" .3. cut ">" - .. :cut -d'>' -f2 - 2-3 , - :wget-qO - http://download.bg | grep -oP '2\>[\d\w .]*' | cut -d'>' -f2

    grep . "grepexamples", "grep tutorials" .

    :

    sudo apt-get install fortune-modecho;fortune;echo

    ...

    sed

    sed . , ! " "! - , sed -. .

    (Regular Expressions RegEx). sed, , - . -.- sed (), "s":echo den | sed s/den/nosht/

    (den) (nosht). () , ?! -

  • 8/8/2019 --bash-scripting

    22/117

    , , "" ( - stdout). UNIX new . , , :sed s/Deniat/Noshtta/ new# old :#Deniat nastypva s purpurna voiska.# , new :#No

    , sed, :sed []/// "/". ! " " :) ( !) @ ( ?), , "|". , , ! "/", sed . "\":echo delimo/delitel | sed 's/delimo/delitel/del/delit/'

    sed . , .

    2 - sed.

    - & . , . , , , :sed 's/nosht/(nosht)/' - , "&". , :sed 's/[a-z]*/(&)/'

    , "&". -. :echo 'nosht 1253' | sed 's/[a-z]*/& &/'# :#nos

    [a-z] - "a" "z". "*" .

    sed- (* , ):Sed a\ .c\ .d .i\ .p .r .s . .

    w .Sed -e SCRIPT - , .-f - , .-n .-V .

  • 8/8/2019 --bash-scripting

    23/117

    , ls:ls -l | sed s/^-[-rwx]*/:/ | sed s/^d[-rwx]*

    [AWK - ]

    , -. awk .. , - . ...

    if ... else ... fi elif

    . , 1, 1.:if [then] else [else] fifi

    . gedit :#!/bin/sh## , if [ $# -eq 0 ]thenecho http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html - - exit 1. linux "0". "0", . Linux . piping .--, ... isnump_n, :chmod 755 isnump_nchmod +x isn

    , (cd ...) . :isnump_n 23

    if-else-fi . .- . elif. - ... ---! , ! :if [ 1 ]then

    ...

    elif [ 2 ]then

    ... elif [ 3 ]then

    ...

    else

  • 8/8/2019 --bash-scripting

    24/117

    ...

    fi

    "0". , elif .#!/bin/sh## , a e e, "0"if [ $# -eq 0 ]

    thenecho "$0 : "exit 1fi

    if test $1 -gt 0then

    echo "$1 "elif [ $1 -eq 0 ]

    , test ! if . , , :#!/bin/bashecho -n " : "read myfileecho -n " ( yes no ) ? "read confirmationconfirmation="$(echo ${confirmation} | tr A-Z a-z)"if [ "$confirmation" == "yes" ]; then"--yle="color: #66cc66;">[ -f $myfile ] && /bin/rm $myfile || echo

    , , chmod +x 755. . , :)... , !

    ... awk, for, pipeline,

    . , . PID-a bash :psaux | grep bashhttp://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html#!/bin/bash.. phrozencrew 16.11.09 22:11

    http://new.download.bg/index.php?cls=forum&mtd=thread&t=224992&q=bash

    http://new.download.bg/index.php?cls=forum&mtd=thread&t=224992&q=bashhttp://new.download.bg/index.php?cls=forum&mtd=thread&t=224992&q=bash
  • 8/8/2019 --bash-scripting

    25/117

    Inventive / 05.02.2005 12:58 http://mytech.bg/uroci/22//319/Bash+Scripting+TutorialBash Scripting Tutorial

    1. 2. Hello, World script3. 4. (user input),

  • 8/8/2019 --bash-scripting

    26/117

    Hello, World$

    - tutorial-a . hello . ,

    , Hello, World. "#".

    #!/bin/bash

    # echo "Hello, World" #

    ###########################################################

    [--- ---]

    ( (=)). , .:

    num=10

    , . (num= 10), bash "num=" 10.

    ($). Hello, World :

    #!/bin/bash

    var="Hello, World"echo $var

    , , , . : , (.), ($), - (>) - (

  • 8/8/2019 --bash-scripting

    27/117

    echo ""$msg1" is not needed to print '$num1 < $num2 & $num2 > $num1'"

    :

    $ ./primer110 < 20 & 20 > 10$100 > $10Here we can use all of these symbols: ".", ">", "

  • 8/8/2019 --bash-scripting

    28/117

    $# -

    $* $@ for-in. - .

    #!/bin/bash

    echo "The first argument is $1, the second $2"echo "All arguments you entered: $*"

    echo "There are $# arguments"

    :

    $ ./primer5 arg1 arg2 arg3 arg4The first argument is arg1, the second arg2All arguments you entered: arg1 arg2 arg3 arg4There are 4 arguments$

    , . .

    , . . export.

    #!/bin/bash

    # .

    var=100export var./primer6-a

    # EOF

    #!/bin/bash

    # .

    echo "The value of var is $var"

    # EOF ( primer6-a,

    , ).

    $ ./primer6The value of var is 100$

  • 8/8/2019 --bash-scripting

    29/117

    declare. :

    declare - --

    :

    -r - readonly-i - integer ( )- - array ()

    -x - export

    :

    #!/bin/bash

    declare -i var # integervar=100echo $vardeclare -r var2=123.456 # readonly echo $var2

    var2=121.343 # var2echo $var2 # var2 123.456 :

    $ ./primer7100123.456bash: var2: readonly variable123.456$

    bash manual pages (man bash).

    ###########################################################

    [--- User input,

  • 8/8/2019 --bash-scripting

    30/117

    :

    #!/bin/bash

    cat

  • 8/8/2019 --bash-scripting

    31/117

    :$ ./primer10

    Enter the first number: 10Enter the second: 310 + 3 = 1310 * 3 = 30110$

    - let.

    + - - - * - / - % - > - -< - ->= - -

  • 8/8/2019 --bash-scripting

    32/117

    :

    #!/bin/bash

    var1=10var2="m000"[ $var1 -eq 10 ]echo $?[ $var2 = "me0w" ]

    echo $?

    :

    $ ./primer1101$

    - test:

    -gt (greater than) - -lt (less than) - -ge (greater or equal) - -le (less or equal) - -eq (equal) -ne (not equal) -z = != -f -s -r -w -x

    , . test manual pages (mantest).

    if . . . if fi case esac. :

    if then 0.

    fi

    if then 0 if,

    else.else

    fi

    if then elif if .

  • 8/8/2019 --bash-scripting

    33/117

    elif then

    else

    fi

    case in case , ) ( .;;

    *) ;;esac

    && (AND)

    || (OR)

    ! (NOT)

    - :

    #!/bin/bash

    echo -n "Enter a string: "read str1echo -n "Enter a string: "read str2echo -n "Enter a number: "read num1

    if [ $str1 == "m000" ]; then # ';' then echo "str1 = m000"

    elif [ $str1 == "m000" ] && [ $str2 == "m000" ]; then # , .. echo "str1 and str2 = m000" # true

    echo "str1 and str2 = m000"else

    echo "str1 and str2 != m000"fi

    if [ -f "/etc/passwd" ]; then # cat /etc/passwd

    fiif [ $num1 -eq 10 ]; then

    echo "num1 = 10"elif [ $num1 -gt 100 ]; then

    echo "num1 > 100"else

    echo "?!?"fi

    :

    $ ./primer12Enter a string: m000Enter a string: m000Enter a number: 10str1 = m000root:x:0:0::/root:/bin/bash

  • 8/8/2019 --bash-scripting

    34/117

    bin:x:1:1:bin:/bin:daemon:x:2:2:daemon:/sbin:adm:x:3:4:adm:/var/log:nobody:x:99:99:nobody:/:sftp:x:1000:100:,,,:/home/sftp:/bin/bashnum1 = 10$

    . case:

    #!/bin/bash

    echo -n "Enter an option (l, s or al): "read opt

    case $opt inl)

    ls -l;;s)

    ls -s;;al)

    ls -al;;*) # $opt

    ls;;esac

    :$ ./primer13

    Enter an option (l, s or al): ltotal 964drwxr-xr-x 33 sftp users 4096 24 19:58 booksdrwxr-xr-x 5 sftp users 4096 12 19:35 docsdrwxr-xr-x 7 sftp users 4096 6 12:34 ircddrwxr-xr-x 2 sftp users 4096 25 23:22 moviesdrwxr-xr-x 7 sftp users 4096 17 11:56 phundrwxr-xr-x 10 sftp users 4096 8 15:54 sourcedrwxr-xr-x 2 sftp users 4096 1 15:27 stuffdrwxr-xr-x 2 sftp users 4096 15 08:40 work$

    . test .###########################################################

    [--- ---]

    . while, until, for for-in.while until for for-in . -:

    while do while 0 (true).

    doneuntil do until

    1 (false).done

    for in

  • 8/8/2019 --bash-scripting

    35/117

    do .

    done

    for for . do .

    done

    while 0. done.

    #!/bin/bash

    m00=yes

    while [ $m00 == "yes" ]; doecho -n "Enter a string: "

    read str1echo "You entered: $str1"echo -n "Do you want to continue? "read m00

    done

    yes, [ $m00 == "yes" ] 1 (false). :

    $ ./primer14Enter a string: asdYou entered: asdDo you want to continue? yesEnter a string: asd1234123You entered: asd1234123Do you want to continue? no$ until:

    #!/bin/bash

    m00=yes

    until [ $m00 == "no" ]; doecho -n "Enter a string: "read str1echo "You entered: $str1"echo -n "Do you want to continue? "read m00

    done

    , [ $m00 == "no" ] e false.

    $ ./primer15Enter a string: me0wYou entered: me0wDo you want to continue? yesEnter a string: zmpf

  • 8/8/2019 --bash-scripting

    36/117

    You entered: zmpfDo you want to continue? no$

    for-in .

    #!/bin/bash

    for cfile in ~/source/c/*.c # for cfile in $( ls ~/source/c/*.c )do

    echo $cfiledone

    :

    $ ./primer16/home/sftp/source/c/a.c/home/sftp/source/c/tmp.c

    /home/sftp/source/c/zmpf.c$

    for e for-in, .

    #!/bin/bash

    for m00do

    echo $m00done

    $@, for-in.

    #!/bin/bash

    for m00 in $@do

    echo $m00

    done :

    $ ./primer17 m00 me0w m33p zmpf lkmnpm00me0wm33pzmpflkmnp$

    , . true, false brea.true - 0. false , 1. break .

  • 8/8/2019 --bash-scripting

    37/117

    #!/bin/bash

    declare -i var=0

    while true; do # false echo -n $varvar=$var+1if [ $var -eq 10 ]; then # $var 10

    break

    fidone

    echoecho bye

    until false :

    while true; do

    until false; do

    ###########################################################

    [--- ---]

    , (). stderr. , . > .:

    $ echo m000 > file$ cat filem000$

    >>, > .

    #!/bin/bash

    nums="1 2 3"

    for num in $numsdo

    echo $numdone > nums

    nums.

    $ ./nums$ cat nums123$

  • 8/8/2019 --bash-scripting

    38/117

    , . - tar gzip.

    $ tar cvf - files/ | gzip -9 > files.tar.gz

    $ gzip -cd files.tar.gz | tar xvf -

    bash .

    #!/bin/bash

    names="Ivan Koljo Asen Sasho Misho"

    for name in $namesdo

    echo $namedone | sort > names

    echo $name sort names.

    $ ./names$ cat namesAsenIvanKoljoMishoSasho$

    sort.

    ###########################################################

    [--- trap ---]

    trap. trap . . trap.

    $ trap '' --

    ( CTRL+C).

    #!/bin/bash

    trap 'echo "Bye"; exit 1' 2

    echo "Enter a string: "read m00echo "nah"

    :

  • 8/8/2019 --bash-scripting

    39/117

    $ ./trap-exEnter a string:^CBye$

    CTRL+C echo "Bye" exit 1, . :

    0

    2 CTRL+C9 kill kill- , trap24 CTRL+Z,

    kill kill manual pages.

    ###########################################################

    [--- ---]

    var[xx]="aa", xx e declare -a

    . ('{' '}').:

    #!/bin/bash

    array[1]=m00array[34]=me0warray[40]=123

    echo "array[1] = ${array[1]}"echo "array[34] = ${array[34]}"echo "array[40] = ${array[40]}"

    array=( x y z ... )

    array[0] ( 0 1), y - array[1], z - array[2] ..

    , :#!/bin/bash

    declare -a array # declare

    echo -n "Enter some numbers separated by space: "read -a array # ( read '-a')

    elements=${#array[@]} # elements

    # ${array[@]} . for-in# :# for i in ${array[@]; do# echo $i# done

    # while

  • 8/8/2019 --bash-scripting

    40/117

    i=0

    while [ $i -lt $elements ]; doecho ${array[$i]}let "i = $i + 1"

    done

    echo "bye"

    :

    $ ./primer18Enter some numbers separated by space: 1 13 14 88 19113148819bye

    $

    ( .) Advanced BashScripting(http://www.tldp.org/LDP/abs/html/arrays.html)

    ###########################################################

    [--- ---]

    bash . :

    __ { }

    __() { }

    .

    #!/bin/bashfunc() {

    echo "Hello"echo "This is function"

    }

    info() {echo "host uptime: $( uptime )"echo "date: $( date )"

    }

    funcinfo

    echo "That's all folks :)"

    :

  • 8/8/2019 --bash-scripting

    41/117

    $ ./primer19HelloThis is functionhost uptime: 1:46pm up 5 days, 14:39, 1 user, load average: 0.08, 0.05, 0.04date: 15 13:46:23 UTC 2002That's all folks :)

    $

    ###########################################################

    [--- ---]

    tutorial-a bash. printf. e[X;XXm, - . -:

    0;30 1;30 0;34 1;34 0;32 1;32Cyan 0;36 Light Cyan 1;36

    0;31 1;31 0;35 1;35 0;33 1;33 0;37 1;37 2J (thanks zEAL)

    :

    #!/bin/bash

    printf "e[2J"printf "e[0;34mbluen" # n printf "e[0;32mgreenn"printf "e[0;37mand back to default color ...n"

  • 8/8/2019 --bash-scripting

    42/117

    BASH - ,

    cleaver 12, 2008 20:48

    Unix-. - " ". , , . , ( ), . -. . - - BASH ( ) ,

    . BASH , . , BASH , , , , . - , Enter . , BASH . - ;, . , . Enter, . - \, . Enter, , ,

    . , , Enter \ . 3 . '~' (tilde) . '/home/myname' '~', . '.' () . , . '..' ( ) , . , '.', .

    ?

    , BASH (builtins), - , BASH , . BASH , . , . , . ? " " " ". . , . - -

    . ( ) . ( ) , . , , ( ), . . , . , ( ) . , . 'cp'.

    cp -ri --verbose dir1 /destination/directory/

    dir1 , . dir1 /destination/directory/ , ( ) . 3 - 2 . , , . '-ri' '-r -i', . --verbose .

  • 8/8/2019 --bash-scripting

    43/117

    . -r 'recursive'. 'cp' dir1, , . -i 'interactive'. , , ( ) ( 'y' 'n' '' ''). --verbose 'cp' ( ) . , . '--verbose' '-v'.

    BASH. . 'cp' - /destination/directory/. . - /. , , . , , , , . , , . - dir1. ' '. ,

    . , ( /), , , . 'dir1' /usr/source/dir1', '/usr/source', , -. '/usr/proba/' , , 'dir1' 'proba', - 'source'. , , , . , . ( ) .

    /. .

    . input output . . , . 'ls' . , , . '>'. :

    ls > list.file

    'ls' '-l' . 'grep' ( ls) , '.jpg'( ). BASH, aa - - . , , , - . - ( ), , . , , .jpg , .

    :ls | grep .jpg | sort -r | gzip > /home/myname/Desktop/lsss.gz

    ? 'ls' , 'grep', , '.jpg' 'sort' . sort' ( '.jpg') 'gzip', lsss.gz .

  • 8/8/2019 --bash-scripting

    44/117

    - : BASH, - .

    1. .

    pwd (=Print Working Directory) - .hostname - (, ).whoami - (, ).

    date - / .time - .who - .finger [user_name] - .last - , , .history - BASH .uptime - , .ps - , . -e, .top - ( ),

    (, ).uname - . -a, , , .free - .df -h - .du -h /dir - , , .

    .

    cat - .echo - , .man - , .ls - . -l , -a .cd [directory] (=Change Directory) - . , .cp [file1 file2 ...] [destination] - . -r (=recursive) .mv - .rm - . -r (=recursive) .

    less - , . .find / -name "filename" - "filename" ( /) .touch - , .kill PID - . -9 .killall - , . .useradd - , .userdel - , .passwd - / . ( root) . root .

    chmod - .

  • 8/8/2019 --bash-scripting

    45/117

    Bash http://wiki.linuxfan.org/index.php/Bash

    $ FULLPATH='/usr/local/etc/rc.d/runme.sh'$ basename ${FULLPATH}

    runme.sh

    $ FULLPATH='/usr/local/etc/rc.d/runme.sh'$ echo ${FULLPATH%/*}

    /usr/local/etc/rc.d

    NAT#!/bin/bash# opengate.ssh script

    # redirect ports for NAT-ed hosts/bin/ping -i 30 linuxfan.org 1> /dev/null 2> /dev/null &while (true) do/usr/bin/ssh -n -N -R 2222:127.0.0.1:22 -R 2223:127.0.0.1:10001 [email protected] $0 disconneted!sleep 30

    done

    ( Caps Lock)#!/bin/bash

    # a script to setup your language in x window# setup the localeunset lc_alllang=bg_bglanguage=bg:en_ukexport lang language# setup the keyboardsetxkbmap -types complete -compat 'complete+leds(scroll)' -geometry 'pc(pc102)' \

    -symbols \'en_us(pc101)+bg(phonetic_enhanced)+group(alt_shift_toggle)+group(rwin_switch)+level3(menu_switch)'# nls for old motif applications

    if test -d /usr/x11r6/lib/x11/nls; thenxnlspath=/usr/x11r6/lib/x11/nlsexport xnlspath

    fi# add custom user fonts pathif [ -f ${home}/.fonts/fonts.dir ]; then

    xset fp+ ${home}/.fontsfi# add system-wide fonts path for cyrfonts (this is not for debian)if [ -f /opt/cyrfonts/fonts.dir ]; then

    xset fp+ /opt/cyrfonts

    fi# read the user resources databaseif test -f ~/.xresources; then

    xrdb -merge ~/.xresourcesfi# disable caps-lock. evil key :-)xmodmap -e "remove Lock = Caps_Lock"

    http://wiki.linuxfan.org/index.php/Bashhttp://wiki.linuxfan.org/index.php/Bash
  • 8/8/2019 --bash-scripting

    46/117

    default gateway

    #!/bin/sh# stupid script to change default gateway# author t0d0r at linuxfan dot org# vim:ts=4:sw=4:

    primary_gateway='217.79.66.2'secondary_gateway='10.210.0.1'

    ping_cmd='/sbin/ping'

    change_to() {/sbin/route delete default/sbin/route add default $1

    }

    current_gateway=`/usr/bin/netstat -rn | /usr/bin/grep default | /usr/bin/awk '{print $2}'`

    ${ping_cmd} -c 3 ${current_gateway} 2>&1 > /dev/null && is_ok=true

    if [ "x_${current_gateway}" = "x_${primary_gateway}" ]; thenif [ "x${is_ok}" = "xtrue" ]; then

    exit;else

    ${ping_cmd} -c 3 ${secondary_gateway} 2>&1 > /dev/null \&& change_to ${secondary_gateway}

    exit;fielse

    ${ping_cmd} -c 3 ${primary_gateway} 2>&1 > /dev/null \&& change_to ${primary_gateway}

    exit;fi

  • 8/8/2019 --bash-scripting

    47/117

    #!/usr/local/bin/bash#Script for test connection from gateway to client#Author: Peter Petrov aka peterpetOS_TYPE=`uname`PW=( 64 1024 1400 19000 25100 )ping_l=`which ping`if [ "x$1" = "x" ]; then

    echo ": ./vrazka "exit 1fiif [ "$OS_TYPE" = "Linux" ]thenecho " Linux"echoecho "......... ...."echoecho

    for i in ${PW[@]}doiz=`${ping_l} -c 10 -s $i $1 | grep loss | awk '{print $6}'`echo ""

    if [ "$iz" = "100%" ];thenecho " FIREWALL"echo " "exitfi

    echo " "$1" "$i" e: "$iz" "donefi

    if [ "$OS_TYPE" = "FreeBSD" ]then

    echo " FreeBSD"INTERFACE=`route get $1 | grep interface | awk '{print $2}'`echo "$INTERFACE"sudo /usr/local/sbin/arping -c 3 -i "$INTERFACE" "$1"

    echoecho "......... ...."echoecho

    for i in ${PW[@]}doiz=`sudo ${ping_l} -c 10 -s $i $1 | grep loss | awk '{print $7}'`echo ""

    if [ "$iz" = "100%" ];

    thenecho " FIREWALL"echo " "exitfi

    echo " "$1" "$i" e: "$iz" "done

  • 8/8/2019 --bash-scripting

    48/117

    fiecho ""echo ""echo "########################### ########################"exit

    differential backup

    #!/bin/bash# backup script by todor.dragnev at gmail.com# useful for daily backup of AWS instancesprefix=/vol/backup/instances/`hostname`exclude_file="$prefix/rsync.exclude"compare_dest=${prefix}/`date +"%Y-%m-01"`/source=/target=$prefix/`date +"%Y-%m-%d"`/# do differential backupif [ -d $compare_dest ]; then

    rsync -ab --compare-dest=${compare_dest} \--exclude-from=${exclude_file} \${source} ${target}

    else# do fullrsync -ab \

    --exclude-from=${exclude_file} \${source} ${compare_dest}

    fi

  • 8/8/2019 --bash-scripting

    49/117

    http://rosoft.org/node/57 02/25/2010 19:05 : rrr . .

    1.

    - . . - ,

    . , - , RS-232 ( ). . , , Alt+F1 F6. , . , .

    - (- ), . . , . , .

    , - telnet ssh.

    - () - , . . , , .

    . , .

    , , , .

    ( ) . /etc/shells. :

    /bin/bash

    /bin/tcsh

    /bin/csh

    /bin/ash

    /bin/ksh

    /bin/zsh

    /bin/rbash

    , . chsh.

    , -s, . :

    #chsh -s login_shell user

    http://rosoft.org/node/57http://rosoft.org/node/57
  • 8/8/2019 --bash-scripting

    50/117

    #chsh

    -l chsh, Slackware .

    , , . - :

    bash bash sh. , , . Bash , , . bash , ksh csh.

    csh , Tab, C.

    tcsh csh, ., csh. csh,

    tsch.

    ksh KornShell e , , .

    zsh ksh. , , . tcsh csh, zsh ksh.

    (bash, ksh, zsh) , r (rbash, rksh, rzsh), . , . restricted /etc/shells , , .

    - bash. - Linux.Bash Bourne Again Shell, Free Software Foundation Bourne shell UNIX.

    2.

    () . . . .

    $ PS1.

  • 8/8/2019 --bash-scripting

    51/117

    :

    $export PS1=%

    %

    .bash_profile .profile, . Slackware bash_profile bash.

    . - bash :

    -r, --restricted . : cd; SHELL, PATH, ENV BASH_ENV; /; / .; / hash; ; >, >|, , >& >>;

    exec; set +r set +orestricted. rbash.

    -rcfile file , .bashrc.

    . . , , , , , , . Bash ,- :

    BASH bash.

    BASH_VESRION .

    GROUPS .

    HOSTNAME .

    OSTYPE bash PWD

    RANDOM 1 32767 .

    UID , bash.

    HISTFILE . ~/.bash_history.

    HISTSIZE , .

    HOME .

    LANG . .

  • 8/8/2019 --bash-scripting

    52/117

    LC_MESSAGES .

    PATH .

    echo:

    $echo $HOME

    /home/student

    $

    export:

    $export HOME=/home/ftp

    $echo $HOME

    /home/ftp

    $

    , , .

    , , .

    3. bashBash , , . Bash , , bash , , , bash. bash :

    $cat > simple_script

    echo "Building file...."

    ls -l /dev > dev_list

    echo "Number of files:"

  • 8/8/2019 --bash-scripting

    53/117

    wc -l dev_list

    rm dev_list

    echo "Exiting"

    Ctrl+D

    $chmod +x simple_script

    $./simple_scipt

    Building file....

    Number of files:

    2633 dev_list

    Exiting

    $

    . , . . installpkg, pkgtool ., , Slackware. kdialog dialog KDE . pkgtool netconfig.

    , .

    4.

    - useradd - ;

    - userdel - ;

    - usermod - ;

    - passwd - . /etc/passwd /etc/shadow.

    - groupadd - ;

    - groupdel - ;

    - groupmod - ;

  • 8/8/2019 --bash-scripting

    54/117

    - groups - . /etc/group

    - su - . su root. exit

    5.

    - ls (dir) - . : -l, -S . : man ls

    - cd -

    - mkdir -

    - cat -

    - head -

    - tail -

    - vi - . "i". : Esc, :, q, Enter , - Esc, :, wq, Enter

    - cp -

    6.

    - chmod -

    - chown -

    - chkgrp -

    7. :

    - echo - . ">" . . : echo > vreme.txt

    - man - . : man ls - ls.

    - df - (root , , : /mnt/win_c - C: Windows)

    - free - RAM - ,

    - wall - . CTRL+D

    - clear -

    - date -

    - uptime - , ,

  • 8/8/2019 --bash-scripting

    55/117

    1, 5 15

    - w -

    - ps-

    - mc- Midnight Commander ( ) - , NortonCommander

    - telnet, ssh -

    - netstat -

  • 8/8/2019 --bash-scripting

    56/117

    BASH : 1.2

    http://linux-bg.exco.net/

    X_console. http://xfactor.itec.yorku.ca/~xconsole/

    , Linux BASH (Bourne Again SHell)

    . (Shell) . , Linux . BASH . bash , .

    ? . - - . C, C++, Java.

    (source code) - . (). C Linux Windows 98. Windows 98. ( ) , . . , , - . , . bash . . Perl, Lisp, Tcl.

    ?

    - Linux. , . . Linux - vi, emacs, pico, mcedit.

    !!! root ! !

    . ! root.

    BASH "Hello World" . "Hello World" . :

    #!/bin/bashecho "Hello World"

    bash .

    bash /bin . bash . , Linux . hello.sh. . :

    xconsole$ chmod 700 ./hello.sh

  • 8/8/2019 --bash-scripting

    57/117

    chmod . :

    xconsole$ ./hello.sh

    Hello World

    ! - , , chmod.

    , , ? "Hello World" . ? . echo "Hello World". ? echo. echo , .

    . "Hello World". ls /home/root, ls /home/root. ?

    , echo. foo. . :

    #!/bin/bashfoo "Hello World"

    chmod :

    xconsole$ ./helloHello World

    . echo . printf. printf , C. :

    xconsole$ echo "Hello World"Hello World

    Linux . bash

    , . - , . :

    xconsole$ mkdir trashxconsole$ mv * trashxconsole$ rm -rf trashxconsole$ mkdir trash

    :

    #!/bin/bashmkdir trashmv * trashrm -rf trash

  • 8/8/2019 --bash-scripting

    58/117

    mkdir trashecho "Deleted all files!"

    clean.sh. clean.sh trash, . , . .

    - . . . bash : "#", (#!/bin/bash). . "#" . :

    #!/bin/bash# tazi programa broi chislata ot 1 do 10:for i in 1 2 3 4 5 6 7 8 9 10; do

    echo $idone

    bash, , . . , , .

    , - , "" . . , . :

    #!/bin/bashx=12echo "Stoinosta na promenliwata x e $x"

    x 12 echo. echo "Stoinosta na promenliwata x e $x" x. "=". :

    __=

    "$" . & x echo $x.

    - (environment). env . :

    xconsole$ echo $SHELL

    /bin/bash

    . /etc/profile ~/.bash_profile. echo , . :

    #!/bin/bashecho "Stojnosta na x e 12."

  • 8/8/2019 --bash-scripting

    59/117

    echo "Az imam 12 moliwa."echo "Toj mi kaza che stojnosta na x e 12."echo "Az sym na 12 godini."echo "Kak taka stojnosta na x e 12?"

    x 12 8. ? 12 8. ... 12 x. ? x. ? :

    #!/bin/bashx=12 # stoinosta na promenliwata x e 12 e xecho "Stoinosta na x e $x."echo "Az imam 12 moliwa."echo "Toj mi kaza che stojnosta na x e $x."echo "Az sym na 12 godini."echo "Kak taka stojnosta na x e $x?"

    $x x, 12. x 12 8 x=12 x=8.

    . .

    " " -. - . . :

    #!/bin/bashcp /etc/foo .echo "Done."

    /etc/foo "Done" . . /etc/foo. :

    xconsole$ ./bar.shcp: /etc/foo: No such file or directoryDone.

    . /etc/foo .

    -, /etc/foo , . "" :

    if /etc/code exists, thencopy /etc/code to the current directoryprint "Done." to the screen.

    otherwise,print "This file does not exist." to the screenexit

    bash? ! bash : if, while, until, for, case.

    . if if, fi. . bash.

    if ... else ... elif ... fi - . " (if) , (else) ".

  • 8/8/2019 --bash-scripting

    60/117

    if test. test ,, . bar.sh:

    #!/bin/bashif test -f /etc/foothen

    # file exists, so copy and print a message.cp /etc/foo .echo "Done."

    else# file does NOT exist, so we print a message and exit.echo "This file does not exist."exit

    fi

    then else -. , - . . /etc/foo, , . -f . test:

    -d -e -f -g SGID -r -s 0-u SUID -w -x

    else , . elif, if if. elif "else if". .

    if test , :

    if test -f /etc/foothen

    :

    if [ -f /etc/foo ]; then

    test . C -. , . : ";" . ";" . -. then .

    test . :

    if [ "$name" -eq 5 ]; then

    while ... do ... donewhile . - , "while() , do() done ". :

    #!/bin/bash

  • 8/8/2019 --bash-scripting

    61/117

    while true; doecho "Press CTRL-C to quit."

    done

    true . . true , , . ":":

    #!/bin/bash

    while :; doecho "Press CTRL-C to quit."done

    , . , - . - , :

    #!/bin/bashx=0; # initialize x to 0while [ "$x" -le 10 ]; do

    echo "Current value of x: $x"

    # increment the value of x:x=$(expr $x + 1)sleep 1

    done

    test ( ) x. -le x -(less) (equal) 10. "(while) x - 10, x, 1 x.". sleep 1 . . test:

    x y, :x -eq y x yx -ne y x yx -gt y x - yx -lt y x - y

    x y, :x = y x yx != y x y

    -n x x -z x x

    , - :

    x=$(expr $x + 1)

    x 1. $(...)? ? . , expr $x + 1, x. $(...) :

    #!/bin/bashme=$(whoami)echo "I am $me."

    . - :

  • 8/8/2019 --bash-scripting

    62/117

    #!/bin/bashecho "I am $(whoami)."

    - . . -. $(...).

    until ... do ... done

    until while. , . until "(until) ,(do) ". :

    #!/bin/bashx=0until [ "$x" -ge 10 ]; do

    echo "Current value of x: $x"x=$(expr $x + 1)sleep 1

    done

    . . until x - 10. x 10 . x 9.

    for ... in ... do ... donefor . , 10 :

    #!/bin/bashecho -n "Checking system for errors"for dots in 1 2 3 4 5 6 7 8 9 10; do

    echo -n "."doneecho "System clean."

    , -n echo . -n . dots 1 10. :

    #!/bin/bash

    for x in paper pencil pen; doecho "The value of variable x is: $x"sleep 1

    done

    x paper, , pencil, pen. .

    . .html :

    #!/bin/bashfor file in *; doecho "Adding .html extension to $file..."mv $file $file.htmlsleep 1

    done

  • 8/8/2019 --bash-scripting

    63/117

    "*" "wild card character". " ", . file , . mv file .html .

    case ... in ... esac case if . . :

    #!/bin/bashx=5 # initialize x to 5# now check the value of x:case $x in

    0) echo "Value of x is 0.";;

    5) echo "Value of x is 5.";;

    9) echo "Value of x is 9.";;

    *) echo "Unrecognized value."

    esac

    case x 3- . x 0, 5 9. "Unrecognized value.". , "*" "", " ". x 0, 5, 9, "*". case ";". case if? if. - :

    #!/bin/bashx=5 # initialize x to 5if [ "$x" -eq 0 ]; then

    echo "Value of x is 0."elif [ "$x" -eq 5 ]; then

    echo "Value of x is 5."elif [ "$x" -eq 9 ]; then

    echo "Value of x is 9."else

    echo "Unrecognized value."

    fi

    . . : ", : ', : `. ? .

    ., " .". . :

    xconsole$ mkdir hello world

    xconsole$ ls -Fhello/ world/

    . mkdir hello world , . :

    xconsole$ mkdir "hello world"

  • 8/8/2019 --bash-scripting

    64/117

    xconsole$ ls -Fhello/ hello world/ world/

    . . mkdir hello world .

    . , . . - :

    #!/bin/bashx=5 # stojnosta na x e 5# izpolzwame dwojni kawichkiecho "Using double quotes, the value of x is: $x"# izpolzwame edinichni kawichkiecho 'Using forward quotes, the value of x is: $x'

    ? , . :

    xconsole$ mkdir 'hello world'xconsole$ ls -Fhello world/

    . . - :

    x=$(expr $x + 1)

    expr $x + 1 x. :

    x=`expr $x + 1`

    ? . , - $(...). $(...) - . :

    $!/bin/bashecho "I am `whoami`"

    BASHbash . expr. a , true . true expr . true ":". expr $((...)). $(...) . :

    #!/bin/bashx=8 # stojnosta na x e 8y=4 # stojnosta na y e 4

    # sega shte priswojm sumata na promenliwite x i y na promenliwata z:z=$(($x + $y))echo "Sum na $x + $y e $z"

    - expr $((...)), .

    bash , , , .

  • 8/8/2019 --bash-scripting

    65/117

    :

    + - * / %

    . . bash :

    #!/bin/bashx=5 # initialize x to 5y=3 # initialize y to 3

    add=$(($x + $y)) # sumiraj x sys y i priswoj rezultata na promenliwata addsub=$(($x - $y)) # izwadi ot x y i priswoj rezultata na promenliwata submul=$(($x * $y)) # umnozhi x po y i priswoj rezultata na promenliwata muldiv=$(($x / $y)) # razdeli x na y i priswoj rezultata na promenliwata div

    mod=$(($x % $y)) # priswoj ostatyka pri delenie na x / y na promenliwata mod

    # otpechataj otgoworite:echo "Suma: $add"echo "Razlika: $sub"echo "Projzwedenie: $mul"echo "Quotient: $div"echo "Ostatyk: $mod"

    expr. add=$(($x + $y)), add=$(expr $x + $y), add=`expr $x + $y .

    . . read. read bash , :

    #!/bin/bash# gets the name of the user and prints a greetingecho -n "Enter your name: "

    read user_nameecho "Hello $user_name!"

    user_name. . read ENTER. , read ENTER . ENTER . :

    #!/bin/bash# gets the name of the user and prints a greetingecho -n "Enter your name: "

    read user_name

    # the user did not enter anything:if [ -z "$user_name" ]; then

    echo "You did not tell me your name!"exit

    fi

  • 8/8/2019 --bash-scripting

    66/117

    echo "Hello $user_name!"

    ENTER . . , .

    - . -

    . , . :

    #!/bin/bash

    # functiqta hello() samo izpechatwa syobshteniehello(){

    echo "Wie ste wyw funkciq hello()"}

    echo "Izwikwame funkciqta hello()..."# izwikwame hello() funkciqta wytre w shell skripta:helloecho "Weche izleznahte ot funkciqta hello()"

    . hello() . - . hello() :

    hello

    bash hello(). .

    . function_name(), , function . functionfunction_name(). - function hello():

    function hello(){

    echo "Wie ste wyw funkciq hello()"}

    "()", : "{...}". . . . , :

    #!/bin/bashecho "Izwikwame funkciqta hello()..."

    # call the hello() function:helloecho "Weche izleznahte ot funkciqta hello()"

    # function hello() just prints a messagehello(){

  • 8/8/2019 --bash-scripting

    67/117

    echo "Wie ste wyw funkciq hello()"}

    :

    xconsole$ ./hello.shIzwikwame funkciqta hello().../hello.sh: hello: command not found

    Weche izleznahte ot funkciqta hello()

    . . :

    #!/bin/bash# admin.sh - administrative tool

    # function new_user() creates a new user accountnew_user(){

    echo "Preparing to add a new user..."

    sleep 2adduser # run the adduser program

    }

    echo "1. Add user"echo "2. Exit"

    echo "Enter your choice: "read choice

    case $choice in1) new_user # call the new_user() function

    ;;*) exit

    ;;esac

    root, adduser root . .

    trap . . CTRL-C interrupt , "" . trap , . trap :

    trap dejstwie signal

    dejstwie , signal . trap -l.

    , SIG. SIGINT, INT. . SIGINT 2.

  • 8/8/2019 --bash-scripting

    68/117

    :

    #!/bin/bash# using the trap command

    # da se zipylni funkciqta sorry() pri natiskane na CTRL-C:trap sorry INT

    # function sorry() prints a message

    sorry(){echo "I'm sorry Dave. I can't do that."sleep 3

    }

    # count down from 10 to 1:for i in 10 9 8 7 6 5 4 3 2 1; do

    echo $i seconds until system failure."sleep 1

    done

    echo "System failure."

    CTRL-C. . trap , sorry(). trap "''" . trap "-". :

    # izpylni sorry() funkciqta kogato programa poluchi signal SIGINT:trap sorry INT

    # nakaraj programata da NE prihwashta SIGINT signala :trap - INT

    # ne prawi nishto kogato se prihwane signal SIGINT:trap '' INT

    trap , , "". trap , .

    AND OR

    . . AND ( "&&") OR ( "||"). AND :

    _1 && _2

    AND - . . . _1 ( false), _2 . :

    if() _1 , AND() if() _2 , then()...

  • 8/8/2019 --bash-scripting

    69/117

    AND :

    #!/bin/bashx=5y=10if [ "$x" -eq 5 ] && [ "$y" -eq 10 ]; then

    echo "I dwete uslowiq sa wqrni."else

    echo "Uslowiqta ne sa wqrni."

    fi

    , x y . x x=5 x=12, , ( false).

    OR . , - (. false). , -:

    _1 || _2

    :

    if() _1 , OR() _2 , ...

    :

    #!/bin/bashx=3y=2if [ "$x" -eq 5 ] || [ "$y" -eq 2 ]; then

    echo "Edno ot uslowiqta e wqrno."else

    echo "Nito edno ot uslowiqta ne e wqrno."fi

    , . y . , ..

    , , if AND OR . if . " if " if if . , if. if, AND :

    #!/bin/bashx=5y=10if [ "$x" -eq 5 ]; then

    if [ "$y" -eq 10 ]; thenecho "I dwete uslowiq sa wqrni."

    elseecho "Uslowiqta ne sa wqrni."

    fifi

    AND . , . AND OR .

    , Linux . ,

  • 8/8/2019 --bash-scripting

    70/117

    . more. , . . "$#". . :

    xconsole$ foo argument

    $# 1 , . , $# 2. (

    - foo) $0 - foo,$1 -argument .. 9 $0 $9. :

    #!/bin/bash# izpechataj pyrwiq argument# proweri dali ima pone edin argument:if [ "$#" -ne 1 ]; then

    echo "usage: $0 "fi

    echo "Stojnosta na argumenta e $1"

    . , , . . , $0 . "usage" .

    PIPING, , .:

    xconsole$ echo "Hello World"Hello World

    "" . . ">" . . :

    xconsole$ echo "Hello World" > foo.filexconsole$ cat foo.fileHello World

    echo "Hello World" foo.file. . ">". , , . ? : ">>". , , .

    piping. Piping- . Piping : "|"., "L".

    SHIFT \. piping:

    xconsole$ cat /etc/passwd | grep xconsolexconsole:x:1002:100:X_console,,,:/home/xconsole:/bin/bash

    /etc/passwd grep, , xconsole .

  • 8/8/2019 --bash-scripting

    71/117

    :

    xconsole$ cat /etc/passwd | grep xconsole > foo.filexconsole$ cat foo.filexconsole:x:1002:100:X_console,,,:/home/xconsole:/bin/bash

    . /etc/passwd , grep xconsole. foo.file. , piping .

    . . . . , . . "$$" , . : hello. , . hello.$$ $$hello, . :

    xconsole$ touch helloxconsole$ lshelloxconsole$ touch hello.$$xconsole$ lshello hello.689

    .

    () ., grep, , grep 0 , 1 . ? . , . grep /etc/passwd. , foobar:

    xconsole$ grep "foobar" /etc/passwdxconsole$

    . grep . - , . . , . $?. :

    #!/bin/bash# grep for user foobar and pipe all output to /dev/null:grep "foobar" /etc/passwd > /dev/null 2>&1# capture the return value and act accordingly:if [ "$?" -eq 0 ]; then

    echo "Match found."

    exitelseecho "No match found."

    fi

    "$?" grep. 0, . , ,

  • 8/8/2019 --bash-scripting

    72/117

    . , . , , -.

    2>&1 . Linux, . 0 (: ), 1 (: ) 2 (: ). 1, 2. /dev/null. ,

    . :

    xconsole$ ls /rootls: /root: Permission deniedxconsole$ ls /root 2> /dev/nullxconsole$

    . 1. , /dev/null.

    , :

    xconsole$ ls /root > /dev/null 2>&1

    /dev/null, .

    ? exit - . 0 , , .. . - - 0 , . . :

    #!/bin/bashif [ -f "/etc/passwd" ]; then

    echo "Password file exists."exit 0

    elseecho "No such file."exit 1

    fi bash . bash . , . bash . - C Perl..

  • 8/8/2019 --bash-scripting

    73/117

    http://bg.wikibooks.org/wiki/____BASH_ BASH

    X_console. http://xfactor.itec.yorku.ca/~xconsole/. , Linux BASH (BourneAgain SHell) . (Shell) . , Linux .

    BASH . bash , . ? . - - . C, C++, Java. (source code) - . (). C Linux Windows 98. Windows 98. ( ) , .

    . , , - . , . bash . . Perl, Lisp, Tcl. ? - Linux. , . . Linux - vi, emacs, pico,mcedit. !!! root ! ! . ! root. BASH "Hello World" . "Hello World" . :!/bin/bash

    echo "Hello World" bash . bash /bin . bash . , Linux . hello.sh.

    . : xconsole$ chmod 700 ./hello.sh chmod . : xconsole$ ./hello.sh

    Hello World ! - , , chmod. , , ? "Hello World" . ? . echo "Hello World". ? echo. echo , .

    . "Hello World". ls /home/root, ls /home/root. ? , echo. foo. . :!/bin/bash

    http://bg.wikibooks.org/wiki/??????_??_?????????_??_BASH_???http://bg.wikibooks.org/wiki/??????_??_?????????_??_BASH_???
  • 8/8/2019 --bash-scripting

    74/117

    foo "Hello World" chmod : xconsole$ ./helloHello World . echo . printf. printf , C. : xconsole$ echo "Hello World"Hello World Linux . bash , . - ,

    . : xconsole$mkdir trash xconsole$ mv * trash xconsole$ rm -rf trash xconsole$ mkdir trash :!/bin/bash

    mkdir trash mv * trash rm -rf trash mkdir trash echo "Deleted all files!" clean.sh. clean.sh trash, . , . . - . .

    . bash : "#", (#!/bin/bash). . "#" . :!/bin/bashtazi programa broi chislata ot 1 do 10:

    for i in 1 2 3 4 5 6 7 8 9 10; do echo $i done bash, , . . , , . , - , "" . . , . :!/bin/bash

    x=12 echo "Stoinosta na promenliwata x e $x" x 12 echo. echo "Stoinosta na promenliwata x e $x" x. "=". : __= "$" . & x echo $x. - (environment).

    env . : xconsole$ echo $SHELL /bin/bash . /etc/profile ~/.bash_profile. echo , . :!/bin/bash

    echo "Stojnosta na x e 12." echo "Az imam 12 moliwa." echo "Toj mi kaza che stojnosta na x e 12." echo "Az symna 12 godini." echo "Kak taka stojnosta na x e 12?" x 12 8. ? 12 8. ...

    12 x. ? x. ? :!/bin/bash

    x=12 # stoinosta na promenliwata x e 12 e x echo "Stoinosta na x e $x." echo "Az imam 12 moliwa." echo "Toj mikaza che stojnosta na x e $x." echo "Az sym na 12 godini." echo "Kak taka stojnosta na x e $x?" $x x, 12. x 12

  • 8/8/2019 --bash-scripting

    75/117

    8 x=12 x=8. . . BASH : 1.2( 2) X_console. http://xfactor.itec.yorku.ca/~xconsole/. e [ 1 ]. " " -. - . . :!/bin/bash

    cp /etc/foo . echo "Done." /etc/foo "Done" . . /etc/foo. : xconsole$ ./bar.sh cp: /etc/foo: No such file or directory Done. . /etc/foo . -, /etc/foo , . "" : if /etc/code exists,then copy /etc/code to the current directory print "Done." to the screen. otherwise, print "This file does not exist." tothe screen exit bash? ! bash : if, while,until, for, case. . if if, fi. . bash. if ... else ... elif ... fi - .

    " (if) ,(else) ". if test. test , , . bar.sh:!/bin/bash

    if test -f /etc/foo thenfile exists, so copy and print a message.

    cp /etc/foo . echo "Done." elsefile does NOT exist, so we print a message and exit.

    echo "This file does not exist." exit fi then else -. , - . . /etc/foo, , . -f . test: -d -e -f -g SGID -r -s 0 -u SUID -w -x

    else , .

    elif, if if. elif "else if". . if test , : if test -f /etc/foo then : if [ -f /etc/foo ]; then test . C -. , . : ";" . ";" . -. then . test . : if [ "$name" -eq 5 ]; then while ... do ... donewhile . - , "while() , do() done ". :

    !/bin/bash

    while true; do echo "Press CTRL-C to quit." done true . . true , , . ":":!/bin/bash

  • 8/8/2019 --bash-scripting

    76/117

    while :; do echo "Press CTRL-C to quit." done , . , - . - , :!/bin/bash

    x=0; # initialize x to 0 while [ "$x" -le 10 ]; do echo "Current value of x: $x"increment the value of x:

    x=$(expr $x + 1) sleep 1 done test ( )

    x. -le x -(less) (equal) 10. "(while) x - 10, x, 1 x.". sleep 1 . . test: x y, : x-eq y x y x -ne y x y x -gt y x - y x -lt y x - y x y, : x = y x y x != y x y -n x x -z x x

    , - : x=$(expr $x

    + 1) x 1. $(...)? ? . , expr $x + 1, x. $(...) :!/bin/bash

    me=$(whoami) echo "I am $me." . - :!/bin/bash

    echo "I am $(whoami)." - . . -. $(...). until ... do ... done until while. , . until "(until) , (do) ". :!/bin/bash

    x=0 until [ "$x" -ge 10 ]; do echo "Current value of x: $x" x=$(expr $x + 1) sleep 1 done . . until x - 10. x 10 . x 9. for ... in ... do ... done for

    . , 10 :!/bin/bash

    echo -n "Checking system for errors" for dots in 1 2 3 4 5 6 7 8 9 10; do echo -n "." done echo "System clean." , -n echo . -n . dots 1 10. :!/bin/bash

    for x in paper pencil pen; do echo "The value of variable x is: $x" sleep 1 done

    x paper, , pencil, pen. . . .html :!/bin/bash

    for file in *; do echo "Adding .html extension to $file..." mv $file $file.html sleep 1 done "*" "wildcard character". " ",

  • 8/8/2019 --bash-scripting

    77/117

    . file , . mv file html . case ... in ... esac case if .

    . :!/bin/bash

    x=5 # initialize x to 5now check the value of x:

    case $x in 0) echo "Value of x is 0."

    5) echo "Value of x is 5."

    9) echo "Value of x is 9.") echo "Unrecognized value."

    esac case x 3- . x 0, 5 9. "Unrecognized value.". , "*" "", " ". x 0, 5,

    9, "*". case ";". case if? if. - :!/bin/bash

    x=5 # initialize x to 5 if [ "$x" -eq 0 ]; then echo "Value of x is 0." elif [ "$x" -eq 5 ]; then echo "Value of x is 5." elif[ "$x" -eq 9 ]; then echo "Value of x is 9." else echo "Unrecognized value." fi BASH : 1.2( 3) X_console. http://xfactor.itec.yorku.ca/~xconsole/. e [ 2 ]. . : : ", : ', : `. ? - . , . , " .". . : xconsole$mkdir hello world xconsole$ ls -F hello/ world/ . mkdir hello world , . : xconsole$mkdir "hello world" xconsole$ ls -F hello/ hello world/ world/ , . . mkdir hello world . , . , . . - :

    !/bin/bashx=5 # stojnosta na x e 5izpolzwame dwojni kawichki

    echo "Using double quotes, the value of x is: $x"izpolzwame edinichni kawichki

    echo 'Using forward quotes, the value of x is: $x' ? , , . , ,

    : xconsole$ mkdir 'hello world' xconsole$ ls -F hello world/ . , . - : x=$(expr $x + 1) expr$x + 1 x. , : x=`expr $x + 1` ? , . , - $(...). $(...) - . : $!/bin/bash echo "I am `whoami`"

  • 8/8/2019 --bash-scripting

    78/117

    BASH bash . , expr. a , , true , . , true expr, . true ":". expr $((...)). $(...) . :!/bin/bash

    x=8 # stojnosta na x e 8 y=4 # stojnosta na y e 4sega shte priswojm sumata na promenliwite x i y na promenliwata z:

    z=$(($x + $y)) echo "Sum na $x + $y e $z" - expr $((...)), . bash , , , , . : + - * / % . - . bash:!/bin/bash

    x=5 # initialize x to 5 y=3 # initialize y to 3 add=$(($x + $y)) # sumiraj x sys y i priswoj rezultata na promenliwataadd sub=$(($x - $y)) # izwadi ot x y i priswoj rezultata na promenliwata sub mul=$(($x * $y)) # umnozhi x po y i

    priswoj rezultata na promenliwata mul div=$(($x / $y)) # razdeli x na y i priswoj rezultata na promenliwata divmod=$(($x % $y)) # priswoj ostatyka pri delenie na x / y na promenliwata modotpechataj otgoworite:

    echo "Suma: $add" echo "Razlika: $sub" echo "Projzwedenie: $mul" echo "Quotient: $div" echo "Ostatyk: $mod" expr. add=$(($x + $y)), add=$(expr $x + $y), add=`expr $x + $y`. . . , read. read bash , , :!/bin/bashgets the name of the user and prints a greeting

    echo -n "Enter your name: " read user_name echo "Hello $user_name!" user_name. , , . read ENTER. , read , ENTER . ENTER , , . :!/bin/bashgets the name of the user and prints a greeting

    echo -n "Enter your name: " read user_namethe user did not enter anything:

    if [ -z "$user_name" ]; then echo "You did not tell me your name!" exit fi echo "Hello $user_name!" ENTER, . . , , , . - . - , . , . , , :

    !/bin/bashfunctiqta hello() samo izpechatwa syobshtenie

    hello() { echo "Wie ste wyw funkciq hello()" } echo "Izwikwame funkciqta hello()..."izwikwame hello() funkciqta wytre w shell skripta:

    hello echo "Weche izleznahte ot funkciqta hello()" .

  • 8/8/2019 --bash-scripting

    79/117

    hello() . - . hello() : hello bash , hello(). . . , function_name(), , function . function function_name(). , function hello(): function hello() { echo "Wie ste wyw funkciq hello()" } "()", : "{...}". . ,

    . . , :!/bin/bash

    echo "Izwikwame funkciqta hello()..."call the hello() function:

    hello echo "Weche izleznahte ot funkciqta hello()"function hello() just prints a message

    hello() { echo "Wie ste wyw funkciq hello()" } , : xconsole$ ./hello.sh Izwikwame funkciqta hello()... ./hello.sh: hello: command not found Wecheizleznahte ot funkciqta hello() , . . :!/bin/bashadmin.sh - administrative toolfunction new_user() creates a new user account

    new_user() { echo "Preparing to add a new user..." sleep 2 adduser # run the adduser program } echo "1. Add user"echo "2. Exit" echo "Enter your choice: " read choice case $choice in 1) new_user # call the new_user() function) exit

    esac root, adduser , root . , . trap< . ., CTRL-C interrupt, "" . trap; , , . trap : trap dejstwie signal dejstwie , , signal , .

    trap -l. , SIG. , SIGINT, INT. . SIGINT 2. :!/bin/bashusing the trap commandda se zipylni funkciqta sorry() pri natiskane na CTRL-C:

    trap sorry INTfunction sorry() prints a message

    sorry() { echo "I'm sorry Dave. I can't do that." sleep 3 }count down from 10 to 1:

    for i in 10 9 8 7 6 5 4 3 2 1; do echo $i seconds until system failure." sleep 1 done echo "System failure." , , CTRL-C. . trap , sorry(). trap "" .

  • 8/8/2019 --bash-scripting

    80/117

    trap "-". :izpylni sorry() funkciqta kogato programa poluchi signal SIGINT:

    trap sorry INTnakaraj programata da NE prihwashta SIGINT signala :

    trap - INTne prawi nishto kogato se prihwane signal SIGINT:

    trap INT trap , , "". trap , , . [ 1| 2 | 3 | 4 ] X_console. http://xfactor.itec.yorku.ca/~xconsole/. e [ 2 ]. . : : ", : ', : `. ? . , . , " .". . : xconsole$ mkdir hello world xconsole$ ls -F hello/ world/ . mkdir hello world , .

    : xconsole$ mkdir "hello world" xconsole$ ls -F hello/ hello world/ world/ , . . mkdir hello world . , . , . . - :!/bin/bash

    x=5 # stojnosta na x e 5izpolzwame dwojni kawichki

    echo "Using double quotes, the value of x is: $x"izpolzwame edinichni kawichki

    echo 'Using forward quotes, the value of x is: $x' ? , , . , , : xconsole$ mkdir 'hello world' xconsole$ ls -F hello world/ . , . - : x=$(expr $x + 1) , expr$x + 1 x.

    : x=`expr $x + 1` ? , . , - $(...). $(...) - . : $!/bin/bash echo "I am `whoami`" BASH bash . expr. a , , true , . , true expr, . true ":". expr $((...)). $(...) . :!/bin/bash

    x=8 # stojnosta na x e 8 y=4 # stojnosta na y e 4

    sega shte priswojm sumata na promenliwite x i y na promenliwata z:

    z=$(($x + $y)) echo "Sum na $x + $y e $z" - expr $((...)), . bash , , , , . : + - * / % . . bash

  • 8/8/2019 --bash-scripting

    81/117

    :!/bin/bash

    x=5 # initialize x to 5 y=3 # initialize y to 3 add=$(($x + $y)) # sumiraj x sys y i priswoj rezultata na promenliwataadd sub=$(($x - $y)) # izwadi ot x y i priswoj rezultata na promenliwata sub mul=$(($x * $y)) # umnozhi x po y ipriswoj rezultata na promenliwata mul div=$(($x / $y)) # razdeli x na y i priswoj rezultata na promenliwata divmod=$(($x % $y)) # priswoj ostatyka pri delenie na x / y na promenliwata modotpechataj otgoworite:

    echo "Suma: $add" echo "Razlika: $sub" echo "Projzwedenie: $mul" echo "Quotient: $div" echo "Ostatyk: $mod" expr. add=$(($x + $y)), add=$(expr $x + $y), add=`expr $x + $y`. . . read. read bash , , :!/bin/bashgets the name of the user and prints a greeting

    echo -n "Enter your name: " read user_name echo "Hello $user_name!" user_name.

    , , . read ENTER. , read , ENTER . ENTER , , . :!/bin/bashgets the name of the user and prints a greeting

    echo -n "Enter your name: " read user_namethe user did not enter anything:

    if [ -z "$user_name" ]; then echo "You did not tell me your name!" exit fi echo "Hello $user_name!" ENTER, . . , , , . - . - , . , . , , :!/bin/bashfunctiqta hello() samo izpechatwa syobshtenie

    hello() { echo "Wie ste wyw funkciq hello()" } echo "Izwikwame funkciqta hello()..."

    izwikwame hello() funkciqta wytre w shell skripta:hello echo "Weche izleznahte ot funkciqta hello()" . hello() . - . hello() : hello bash hello(). . . function_name(), , function . function function_name(). , function hello(): function hello() { echo "Wie ste wyw funkciq hello()" } "()", : "{...}".

    . . . , :!/bin/bash

    echo "Izwikwame funkciqta hello()..."

  • 8/8/2019 --bash-scripting

    82/117

    call the hello() function:

    hello echo "Weche izleznahte ot funkciqta hello()"function hello() just prints a message

    hello() { echo "Wie ste wyw funkciq hello()" } , : xconsole$ ./hello.sh Izwikwame funkciqta hello()... ./hello.sh: hello: command not found Wecheizleznahte ot funkciqta hello() , . . :

    !/bin/bashadmin.sh - administrative toolfunction new_user() creates a new user account

    new_user() { echo "Preparing to add a new user..." sleep 2 adduser # run the adduser program } echo "1. Add user"echo "2. Exit" echo "Enter your choice: " read choice case $choice in 1) new_user # call the new_user() function) exit

    esac , root, adduser , root . , . trap,

    . ., CTRL-C interrupt, "" . trap , , . trap : trap dejstwie signal dejstwie , , signal , . trap -l. , SIG. , SIGINT, INT. . SIGINT 2. :!/bin/bashusing the trap commandda se zipylni funkciqta sorry() pri natiskane na CTRL-C:

    trap sorry INTfunction sorry() prints a message

    sorry() { echo "I'm sorry Dave. I can't do that." sleep 3 }count down from 10 to 1:

    for i in 10 9 8 7 6 5 4 3 2 1; do echo $i seconds until system failure." sleep 1 done echo "System failure." ,

    CTRL-C. . trap , sorry(). trap "" . trap "-". :izpylni sorry() funkciqta kogato programa poluchi signal SIGINT:

    trap sorry INTnakaraj programata da NE prihwashta SIGINT signala :

    trap - INTne prawi nishto kogato se prihwane signal SIGINT:

    trap INT trap , , "". trap , , . BASH : 1.2( 4) X_console. http://xfactor.itec.yorku.ca/~xconsole/. e [ 3 ]. AND OR .

  • 8/8/2019 --bash-scripting

    83/117

    , . AND ( "&&") OR ( "||").AND : _1 && _2 AND - . . . _1 ( false), _2 . : if() _1 , AND() if() _2 , then()... AND :!/bin/bash

    x=5 y=10 if [ "$x" -eq 5 ] && [ "$y" -eq 10 ]; then echo "I dwete uslowiq sa wqrni." else echo "Uslowiqta ne sa

    wqrni." fi , x y , . x x=5 x=12, , ( false). OR . , - (. false). -: _1 ||_2 : if() _1 , OR() _2 , ... :!/bin/bash

    x=3 y=2 if [ "$x" -eq 5 ] || [ "$y" -eq 2 ]; then echo "Edno ot uslowiqta e wqrno." else echo "Nito edno ot uslowiqtane e wqrno." fi , . y . , .

    , , if AND OR . if . " if " if if . , if. if, AND :!/bin/bash

    x=5 y=10 if [ "$x" -eq 5 ]; then if [ "$y" -eq 10 ]; then echo "I dwete uslowiq sa wqrni." else echo "Uslowiqta ne sawqrni." fi fi , AND . , - , . AND OR . , Linux . ; , . more. , . . "$#". . : xconsole$ foo argument $# 1 , . , $# 2. ( - foo) $0 - foo, $1 -argument .. 9 $0 $9. :!/bin/bash

    izpechataj pyrwiq argumentproweri dali ima pone edin argument:

    if [ "$#" -ne 1 ]; then echo "usage: $0 " fi echo "Stojnosta na argumenta e $1" , . , , . , , . , $0 . "usage" . PIPING , , .: xconsole$ echo "Hello World" Hello World "" . . ">"

    . , . : xconsole$ echo "Hello World" > foo.file xconsole$ cat foo.file Hello World echo "Hello World" foo.file. . , ">". , , . , ? : ">>". ,

  • 8/8/2019 --bash-scripting

    84/117

    , . piping.Piping- . Piping : "|". , "L". SHIFT \. piping: xconsole$ cat /etc/passwd | grep xconsole xconsole:x:1002:100:X_console,,,:/home/xconsole:/bin/bash /etc/passwd grep, xconsole , . , : xconsole$ cat /etc/passwd | grep xconsole> foo.file xconsole$ cat foo.file xconsole:x:1002:100:X_console,,,:/home/xconsole:/bin/bash .

    /etc/passwd grep xconsole. foo.file. , piping , . , . . . . , , , . . "$$" . : hello. , . hello.$$ $$hello,

    . : xconsole$ touch hello xconsole$ ls hello xconsole$ touch hello.$$xconsole$ ls hello hello.689 . () , . , grep , , grep 0 , 1 . ? . , . grep /etc/passwd. , , foobar: xconsole$ grep "foobar" /etc/passwdxconsole$ . grep . - , . , , . , . $?. :!/bin/bashgrep for user foobar and pipe all output to /dev/null:

    grep "foobar" /etc/passwd > /dev/null 2>&1capture the return value and act accordingly:

    if [ "$?" -eq 0 ]; then echo "Match found." exit else echo "No match found." fi , "$?" grep. 0,

    . , . , . , , , -. 2>&1, . Linux, . 0 (: ), 1 (: ) 2 (: ). 1, 2. /dev/null. , . , , : xconsole$ ls /root ls: /root: Permission denied xconsole$ ls /root 2>/dev/null xconsole$ , .

    , 1. , /dev/null. , , :xconsole$ ls /root > /dev/null 2>&1 , , /dev/null, . ? exit - ,

  • 8/8/2019 --bash-scripting

    85/117

    . 0 , , , .. . - - 0 , . . :!/bin/bash

    if [ -f "/etc/passwd" ]; then echo "Password file exists." exit 0 else echo "No such file." exit 1 fi bash . , bash . ,

    . bash . - C Perl. !

  • 8/8/2019 --bash-scripting

    86/117

    http://bg.wikipedia.org/wiki/BashBash Bourne Again Shell ( : ) (), UNIX .1 2 3 4 Bash

    5 Bash 6 Bash6.1 6.2 7 Bash

    UNIX, . - UNIX. - Windows

    MacOS, . ( ) (builtins).

    UNIX Bourne shell (sh). UNIX 7 1979 . C shell (csh), BSD. C, C shell UNIX . Bourne shell. Bourne shell ksh (Korn Shell). Bourne shell.

    , Bash (Bourne-Again Shell) - UNIX. sh (Bourne Shell) ksh (Korn Shell) csh (C Shell). 10 1988 . - . 1995 . Bash 2.0 23 1996 . Bash . , . . Bash , sed,

    awk, grep, cut . UNIX.

    Bash

    , *nix . man less, vi .J -- -- L -- H --

    Space -- q --- ( quit ) Ctrl + Z -- , (job) ""fg -- ""clear ; anotherCommand --- ; Ctrl + C ---

    http://bg.wikipedia.org/wiki/Bashhttp://bg.wikipedia.org/wiki/Bash
  • 8/8/2019 --bash-scripting

    87/117

    Bash

    , . .. myFirstScript.sh , :chmod u+x myFirstScript.sh

    ls -al

    , Bash , :#!///bash

    C, C++, Java . Bash , . Bash :#!/usr/local/bin/bashecho ", !"

    # :echo "hello" # hello

    # exit

    Bash . , declare. :ime_promenliva="stoinost na promenlivata"

    $ . :echo $ime_promenliva

    . function:function ime_funciq {# kod na funciq

    }

    :ime_funciq() {# kod na funciq

    }

    , , :

    ime_funciq " 1" " 2" 5 $1 $n n . shift, :echo $1shift 2# $3 $1 Bash []

    e int , . integer --- :

    int1 -eq int2 True int1 int2int1 -ge int2 True int1 - int2.int1 -gt int2 True int1 - int2.int1 -le int2 True int1 - int2int1 -lt int2 True int1 - int2int1 -ne int2 True int1 int2

  • 8/8/2019 --bash-scripting

    88/117

    string, str .str1 = str2 True str1 str2.str1 != str2 True str1 str2.str True str null (.. )-n str True if str - null(null )-z str True str 0 . (0 null) Bash []

    ls -a -X -1 # ls -al | less # history | grep cd # history , .... grep , cd !345 # 345 command > command_output.txt # command_output.txt ( command )find / -name "filename" # "filename" /find . -name linux | grep bash | less # "linux" ,

    , "bash" less - alias ls='ls -1 -X --color=tty' # Ctrl + A # Ctrl + E # Ctrl + U # Ctrl + K # mkdir /mnt/usbflash # /mnt/usbflash mount /dev/sdb1 -t vfat /mnt/usbflash # vfat umount /mnt/usbflash # cat history.txt | mail -s "test file sending" -c someEmail(a)abv.bg some.otherEmail.com # history.txt , mail "test file sending" head -n 20 tooLongFile # 20 vim /etc/bashrc # PS1="\u@\h \t \w\n\\$ " # $ for file in `ls -R` ; do cp $file $file.bak; done # .bakgunzip *file.ziptar -xvf file.tar #

  • 8/8/2019 --bash-scripting

    89/117

    bash

    bash a , . a PS1. . :

    [slaff@atlantis slaff]$ SAVE=$PS1

    PS1 SAVE. PS1 . PS1 "command>":

    [slaff@atlantis slaff]$ PS1="command>"

    :

    command>

    command> PS1=$SAVE[slaff@atlantis slaff]$

    Bash , . :

    \a \d " " "" " ( "Tue May 26")\h (. subdomain.domain.org -> =subdomain)\H \n \r \s , \t 24 HH:MM:SS (HH-, MM-, SS-)\T 12 HH:MM:SS\u (username)\v bash ( 2.00)\w

    \W \! \nnn o \\ (.. \)\[ " "\] " "

    , :

    \u ( ) . slaff\h . atlantis

    \W . slaff

    [slaff@atlantis slaff]$ PS1="\u@\h \W> "slaff@atlantis slaff> lsbin mailslaff@atlantis slaff>

  • 8/8/2019 --bash-scripting

    90/117

    - Linux . , :

    slaff@atlantis slaff> PS1="[\t][\u@\h:\w]\$ "[21:52:01][slaff@atlantis:~]$ lsbin mail

    , ,

    .bash_profile, . . root /etc/profile /etc/bashrc . , Linux . PS1="[\t][\u@\h:\w]\$ "

    (alias)

    Alias ( ) . "cd /usr/local/share/" GO

    alias GO="cd /usr/local/share/"

    - .bash_profile

    PROMPT_COMMAND

    PROMPT_COMMAND . :

    [21:55:01][slaff@atlantis:~] PS1="[\u@\h:\w]\$ "[slaff@atlantis:~] PROMPT_COMMAND="echo 2155"2155[slaff@atlantis:~] dbin mail2156[slaff@atlantis:~]

    2155 . ,

    2155 . -n echo.

    [slaff@atlantis:~] PROMPT_COMMAND="echo -n 2155"2156[slaff@atlantis:~]$2156[slaff@atlantis:~]$ dbin mail

    -.

    .

    Bash /usr/local/bin lsbytesum. , PATH.

  • 8/8/2019 --bash-scripting

    91/117

    ___________________________________________________#!/bin/bash# lsbytesum - sum the number of bytes in a directory listingTotalBytes=0for Bytes in $(ls -l | grep "^-" | cut -c30-41)dolet TotalBytes=$TotalBytes+$BytesdoneTotalMeg=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc)

    echo -n "$TotalMeg"___________________________________________________

    .

    :

    [2158][slaff@atlantis:~]$ PS1="[\u@\h:\w (\$(lsbytesum) Mb)]\$ "[slaff@atlantis:~ (0 Mb)]$ cd /bin[slaff@atlantis:/bin (4.498 Mb)]$

    . , . . .

    Bash

    RedHat. . . :

    echo -e "\033[41;33;1m Welcome to Linux\033[m"

    "Welcome to Linux" . , "\033[bg;fg;1m \033[m". 41 , , 33 , .

    :

    : 30=, 31=, 32=, 33=, 34=, 35=, 36=,37= : 0=, 40=, 41=, 42=, 43=, 44= 45=,46=, 47=

    echo -e "\033[44;37;1m Welcome to Linux\033[m"

    Slackware Linux___________________________________________________#/bin/bashversion="`cat /etc/slackware-version`"echo -e "\033[41;33;1m Welcome to Slackware $version\033[m"

    ___________________________________________________

    . , \[\033[ m\].

  • 8/8/2019 --bash-scripting

    92/117

    PS1="\[\033[1;34m\][\$(date +%H%M)][\u@\h:\w]$\[\033[0m\] "

    :

    0;30 1;30 0;34 1;34 0;32 1;32 0;36 1;36 0;31 1;31

    0;35 1;35 0;33 1;33 0;37 1;37

    :

    \[\033[44;1;31m\]

    \[\033[44m\]\[\033[1;31m\]

    :4: , 5: , 8:

    ___________________________________________________

    function elite{

    local GRAY="\[\033[1;30m\]"local LIGHT_GRAY="\[\033[0;37m\]"local CYAN="\[\033[0;36m\]"local LIGHT_CYAN="\[\033[1;36m\]"

    case $TERM inxterm*)local TITLEBAR='\[\033]0;\u@\h:\w\007\]';;*)local TITLEBAR=""

    ;;esac

    local GRAD1=$(tty|cut -d/ -f3)PS1="$TITLEBAR\$GRAY-$CYAN-$LIGHT_CYAN(\$CYAN\u$GRAY@$CYAN\h\$LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\$CYAN\#$GRAY/$CYAN$GRAD1\$LIGHT_CYAN)$CYAN-$LIGHT_CYAN(\$CYAN\$(date +%H%M)$GRAY/$CYAN\$(date +%d-%b-%y)\

    $LIGHT_CYAN)$CYAN-$GRAY-\$LIGHT_GRAY\n\$GRAY-$CYAN-$LIGHT_CYAN(\$CYAN\$$GRAY:$CYAN\w\$LIGHT_CYAN)$CYAN-$GRAY-$LIGHT_GRAY "PS2="$LIGHT_CYAN-$CYAN-$GRAY-$LIGHT_GRAY "}

  • 8/8/2019 --bash-scripting

    93/117

    ___________________________________________________

    :

    ___________________________________________________#!/bin/bash## This file echoes a bunch of colour codes to the terminal to demonstrate

    # what's available. Each line is one colour on black and gray# backgrounds, with the code in the middle. Verified to work on white,# black, and green BGs (2 Dec 98).#echo " On Light Gray: On Black:"echo -e "\033[47m\033[1;37m White \033[0m\1;37m \\033[40m\033[1;37m White \033[0m"echo -e "\033[47m\033[37m Light Gray \033[0m\37m \\033[40m\033[37m Light Gray \033[0m"

    echo -e "\033[47m\033[1;30m Gray \033[0m\1;30m \\033[40m\033[1;30m Gray \033[0m"echo -e "\033[47m\033[30m Black \033[0m\30m \\033[40m\033[30m Black \033[0m"echo -e "\033[47m\033[31m Red \033[0m\31m \\033[40m\033[31m Red \033[0m"echo -e "\033[47m\033[1;31m Light Red \033[0m\1;31m \\033[40m\033[1;31m Light Red \033[0m"echo -e "\033[47m\033[32m Green \033[0m\32m \\033[40m\033[32m Green \033[0m"echo -e "\033[47m\033[1;32m Light Green \033[0m\1;32m \\033[40m\033[1;32m Light Green \033[0m"echo -e "\033[47m\033[33m Brown \033[0m\33m \\033[40m\033[33m Brown \033[0m"

    echo -e "\033[47m\033[1;33m Yellow \033[0m\1;33m \\033[40m\033[1;33m Yellow \033[0m"echo -e "\033[47m\033[34m Blue \033[0m\34m \\033[40m\033[34m Blue \033[0m"echo -e "\033[47m\033[1;34m Light Blue \033[0m\1;34m \\033[40m\033[1;34m Light Blue \033[0m"echo -e "\033[47m\033[35m Purple \033[0m\35m \

    \033[40m\033[35m Purple \033[0m"echo -e "\033[47m\033[1;35m Pink \033[0m\1;35m \\033[40m\033[1;35m Pink \033[0m"echo -e "\033[47m\033[36m Cyan \033[0m\36m \\033[40m\033[36m Cyan \033[0m"

  • 8/8/2019 --bash-scripting

    94/117

    echo -e "\033[47m\033[1;36m Light Cyan \033[0m\1;36m \\033[40m\033[1;36m Light Cyan \033[0m"___________________________________________________

    .

    ___________________________________________________#!/bin/bash# "hostloadcolour" - 17 October 98, by Giles## The idea here is to change the colour of the host name in the ,# depending on a threshold load value.

    # THRESHOLD_LOAD is the value of the one minute load (multiplied# by one hundred) at which you want

    # the to change from COLOUR_LOW to COLOUR_HIGHTHRESHOLD_LOAD=200COLOUR_LOW='1;34'# light blueCOLOUR_HIGH='1;31'# light red

    function _command {ONE=$(uptime | sed -e "s/.*load average: \(.*\...\), \(.*\...\), \(.*\...\)/\1/" -e "s/ //g")# Apparently, "scale" in bc doesn't apply to multiplication, but does# apply to division.ONEHUNDRED=$(echo -e "scale=0 \n $ONE/0.01 \nquit \n" | bc)if [ $ONEHUNDRED -gt $THRESHOLD_LOAD ]thenHOST_COLOUR=$COLOUR_HIGH# Light RedelseHOST_COLOUR=$COLOUR_LOW# Light Bluefi}

    function hostloadcolour {

    PROMPT_COMMAND=_commandPS1="[$(date +%H%M)][\u@\[\033[\$(echo -n \$HOST_COLOUR)m\]\h\[\033[0m\]:\w]$ "}

  • 8/8/2019 --bash-scripting

    95/117

    BASH : 1.2( 1) X_console(14-03-2000)

    X_console. http://xfactor.itec.yorku.ca/~xconsole/.

    , Linux BASH (Bourne Again SHell) . (Shell) .

    , Linux . BASH . bash , .

    ? . - - . C, C++, Java. (source code) - .

    (). C Linux Windows 98. Windows 98. ( ) , . . , , - . , . bash . . Perl, Lisp, Tcl.

    ?

    - Linux. , . . Linux - vi, emacs, pico, mcedit.

    !!! root ! ! . ! root.

    BASH "Hello World" . "Hello World" . :

    #!/bin/bashecho "Hello World"

    bash . bash /bin . bash .

    , Linux . hello.sh. . :

    xconsole$ chmod 700 ./hello.sh

    chmod

  • 8/8/2019 --bash-scripting

    96/117

    . :

    xconsole$ ./hello.sh

    Hello World

    ! - , , chmod.

    , , ? "Hello World" . ? . echo "Hello World". ? echo. echo , .

    . "Hello World". ls /home/root, ls /home/root. ? ,

    echo. foo. . :

    #!/bin/bashfoo "Hello World"

    chmod :

    xconsole$ ./helloHello World

    . echo . printf. printf , C. :

    xconsole$ echo "Hello World"Hello World

    Linux . bash , .

    - , . :

    xconsole$ mkdir trashxconsole$ mv * trashxconsole$ rm -rf trashxconsole$ mkdir trash

    :

    #!/bin/bashmkdir trashmv * trashrm -rf trashmkdir trash

  • 8/8/2019 --bash-scripting

    97/117

    echo "Deleted all files!"

    clean.sh. clean.sh trash, . , . .

    - .

    . . bash : "#", (#!/bin/bash). . "#" . :

    #!/bin/bash# tazi programa broi chislata ot 1 do 10:for i in 1 2 3 4 5 6 7 8 9 10; do

    echo $idone

    bash, ,

    . . , , .

    , - , "" . . , . :

    #!/bin/bashx=12echo "Stoinosta na promenliwata x e $x"

    x 12 echo. echo "Stoinosta na promenliwata x e $x" x. "=". :

    __=

    "$" . & x echo $x.

    - (environment). env . :

    xconsole$ echo $SHELL

    /bin/bash

    .

    /etc/profile ~/.bash_profile. echo , . :

    #!/bin/bashecho "Stojnosta na x e 12."echo "Az imam 12 moliwa."

  • 8/8/2019 --bash-scripting

    98/117

    echo "Toj mi kaza che stojnosta na x e 12."echo "Az sym na 12 godini."echo "Kak taka stojnosta na x e 12?"

    x 12 8. ? 12 8. ... 12 x. ? x. ? :

    #!/bin/bashx=12 # stoinosta na promenliwata x e 12 e xecho "Stoinosta na x e $x."echo "Az imam 12 moliwa."echo "Toj mi kaza che stojnosta na x e $x."echo "Az sym na 12 godini."echo "Kak taka stojnosta na x e $x?"

    $x x, 12. x 12 8 x=12 x=8. .

    .

    [ 1] BASH : 1.2( 2)

    X_console(29-03-2000)

    (1) [ ] [ ]

    X_console. http://xfactor.itec.yorku.ca/~xconsole/.

    e [ 1 ].

    " " -.

    - . . :

    #!/bin/bashcp /etc/foo .echo "Done."

    /etc/foo "Done" . . /etc/foo. :

    xconsole$ ./bar.shcp: /etc/foo: No such file or directoryDone.

    . /etc/foo . -, /etc/foo , . "" :

  • 8/8/2019 --bash-scripting

    99/117

    if /etc/code exists, thencopy /etc/code to the current directoryprint "Done." to the screen.

    otherwise,print "This file does not exist." to the screenexit

    bash? ! bash : if, while, until, for, case. . if

    if, fi. . bash.

    if ... else ... elif ... fi - . " (if) , (else) ". if test. test ,, . bar.sh:

    #!/bin/bashif test -f /etc/foo

    then# file exists, so copy and print a message.cp /etc/foo .echo "Done."

    else# file does NOT exist, so we print a message and exit.echo "This file does not exist."exit

    fi

    then else -. , - . . /etc/foo, , . -f . test:

    -d -e -f -g SGID -r -s 0

    -u SUID -w -x

    else , . elif, if if. elif "else if". .

    if test , :

    if test -f /etc/foothen

    :

    if [ -f /etc/foo ]; then

  • 8/8/2019 --bash-scripting

    100/117

    test . C -. , . : ";" . ";" . -. then .

    test . :

    if [ "$name" -eq 5 ]; then

    while ... do ... donewhile . - , "whi


Recommended