SO/LS/LS4

From WikiZMSI

< SO | LS

Spis treści

Pierwszy program

  • Uruchomić dowolny edytor i wpisać
#!/bin/bash
# To jest komentarz
echo "To mój pierwszy skrypt!"
  • Zapisać plik pod nazwą programNo1
  1. Zmień uprawnienia poleceniem
chmod 755 programNo1
  • Uruchom program wpisując:
 ./programNo1
  • Jeżeli w katalogu domowym nie masz katalogu bin, to go utwórz poleceniem
mkdir bin

i wykorzystaj do trzymania swoich programów, w tym napisanych w bash. Przenieś swój program do katalogu bin

  • Dodanie do zmiennej PATH katalog bin, w którym zapisany jest programNo1
export PATH=$PATH:bin
  • Uruchom teraz swój program poleceniem:
programNo1

Skrypty konfiguracyjne

Nazwa Zawartość
/etc/profile Globalny skrypt konfiguracyjny, który dotyczy wszystkich użytkowników.
~/.bash_profile Osobisty plik startowy użytkownika. Może być użyty do rozszerzenia lub nadpisania ustawień w skrypcie konfiguracji globalnej.
~/.bash_login Jeżeli .bash_profile nie istnieje, to bash będzie próbował czytać ten plik
~/.profile Jeśli nie znaleziono ani ~/.bash_profile ani ~/.bash_login, bash próbuje odczytać ten plik. Jest to domyślne w dystrybucjach opartych na Debianie, takich jak Ubuntu.
/etc/bash.bashrc Globalny skrypt konfiguracyjny, który dotyczy wszystkich użytkowników.
~/.bashrc Osobisty plik startowy użytkownika. Może być użyty do rozszerzenia lub nadpisania ustawień w skrypcie konfiguracji globalnej.
  • Przykładowy plik:
# .bash_profile
# Get the aliases and functions
# If the file "~/.bashrc" exists, then read the "~/.bashrc" file.
if [ -f ~/.bashrc ]; then 
    . ~/.bashrc
fi
# User specific environment and startup programs
PATH=$PATH:$HOME/bin
export PATH


Polecenia powłoki podstawione i wartości stałe

  • Dodaj jako paragraph w <body> Treść
< p>Updated on $(date +"%x %r %Z") by $USER</p>
  • $() - oznacza- powiedz powłoce, "zastąp wyniki załączoną komendą".
  • Wykorzystaj następujące zmienne by zmodyfikować swój kod:
right_now=$(date +"%x %r %Z")
time_stamp="Updated on $right_now by $USER"
  • Jeżeli wartość zmiennej nigdy nie ulega zmianie, to użyj zmiennej:
RIGHT_NOW=$(date +"%x %r %Z")
TIME_STAMP="Updated on $RIGHT_NOW by $USER"

Instrukcja warunkowa

  • składnia:
if commands; then
commands
[elif commands; then
commands...]
[else
commands]
fi


  • $? zwraca wartość zakończenia ostatniego wykonanego polecenia. echo $? wypisuje tę wartość na konsoli. zero oznacza pomyślne wykonanie, podczas gdy wartości niezerowe są mapowane do różnych przyczyn niepowodzenia.
ls -d /usr/bin
echo $?
true
echo $?
false
echo $?
  • Wypróbuj
if [ -f .bash_profile ]; then
    echo "Mazz  .bash_profile. OK"
else
    echo "Brak .bash_profile!"
fi
Wyrażenie Opis
-d file True if file is a directory.
-e file True if file exists.
-f file True if file exists and is a regular file.
-L file True if file is a symbolic link.
-r file True if file is a file readable by you.
-w file True if file is a file writable by you.
-x file True if file is a file executable by you.
file1 -nt file2 True if file1 is newer than (according to modification time) file2
file1 -ot file2 True if file1 is older than file2
-z string True if string is empty.
-n string True if string is not empty.
string1 = string2 True if string1 equals string2.
string1 != string2 True if string1 does not equal string2.
  • Testowanie użytkownika:
if [ $(id -u) = "0" ]; then
    echo "superużytkownik"
fi

Rozwiązywanie problemów

  • utworzyć następujący skrypt o nazwie trouble.bash.
#!/bin/bash
number=1

if [ $number = "1" ]; then
    echo "Liczba równa 1"
else
    echo "Liczba różna od 1"
fi
  • Co się stanie po zamienie wiersza drugiego na number=
  • Zamień linijkę z if na:
if [ "$number" = "1" ]; then
  • Tryb śledzenia:
#!/bin/bash -x

lub

set +x

Wejście z klawiatury

  • Utwórz skrypt:
#!/bin/bash

echo -n "Enter some text > " 
read text
echo "You entered: $text"
  • opcja -t - przestaje czytać po określonym oknie czasowym
#!/bin/bash

echo -n "Pospiesz się i napisz coś! > "
if read -t 3 response; then
    echo "Zdążyłeś na czas!"
else
    echo "Niestety nie udało się!"
fi
  • opcja -s nie wyświetla tego, co napisze użytkownik

Obliczenia

  • utwórz skrypt obilczenia.bash
#!/bin/bash

first_num=0
second_num=0

echo -n "Enter the first number --> "
read first_num
echo -n "Enter the second number -> "
read second_num

echo "first number + second number = $((first_num + second_num))"
echo "first number - second number = $((first_num - second_num))"
echo "first number * second number = $((first_num * second_num))"
echo "first number / second number = $((first_num / second_num))" 
echo "first number % second number = $((first_num % second_num))"
echo "first number raised to the"
echo "power of the second number   = $((first_num ** second_num))"
  • Zauważ, że wiodący "$" nie jest potrzebny do odnoszenia się do zmiennych wewnątrz wyrażenia arytmetycznego takiego jak "first_num + second_num".
  • Co robi skrypt?


#!/bin/bash

number=0

echo -n "Podaj liczbę > "
read number

echo "Liczba  $number"
if [ $((number % 2)) -eq 0 ]; then
    echo "jest ????"
else
    echo "jest ???"
fi

Kontrola wykonania

  • Case zamiast instrukcji warunkowej if
#!/bin/bash
echo -n "Wprowadz liczbę od 1 do 3 > "
read character
case $character in
    1 ) echo "You entered one."
        ;;
    2 ) echo "You entered two."
        ;;
    3 ) echo "You entered three."
        ;;
    * ) echo "You did not enter a number between 1 and 3."
esac
  • Uzycie |
#!/bin/bash

echo -n "Type a digit or a letter > "
read character
case $character in
                                # Check for letters
    [ [:lower:]] | [ [:upper:] ] ) echo "You typed the letter $character"
                               ;;
                               # Check for digits
    [0-9] )                     echo "You typed the digit $character"
                               ;;

                                # Check for anything else
    * )                         echo "You did not type a letter or a digit"
esac

Pętle

  • While
#!/bin/bash

number=0
while [ "$number" -lt 10 ]; do
    echo "Number = $number"
    number=$((number + 1))
done
  • Until
#!/bin/bash

number=0
until [ "$number" -ge 10 ]; do
    echo "Number = $number"
    number=$((number + 1))
done
  • Przykład 1
#!/bin/bash

selection=
until [ "$selection" = "0" ]; do
    echo "
    PROGRAM MENU
    1 - Display free disk space
    2 - Display free memory

    0 - exit program
"
    echo -n "Enter selection: "
    read selection
    echo ""
    case $selection in
        1 ) df ;;
        2 ) free ;;
        0 ) exit ;;
        * ) echo "Please enter 1, 2, or 0"
    esac
done
  • Przykład 2
#!/bin/bash

press_enter()
{
    echo -en "\nPress Enter to continue"
    read
    clear
}

selection=
until [ "$selection" = "0" ]; do
    echo "
    PROGRAM MENU
    1 - display free disk space
    2 - display free memory 

    0 - exit program
"
    echo -n "Enter selection: "
    read selection
    echo ""
    case $selection in
        1 ) df ; press_enter ;;
        2 ) free ; press_enter ;;
        0 ) exit ;;
        * ) echo "Please enter 1, 2, or 0"; press_enter
    esac
done

Parametry skryptu

  • Załóżmy wywołanie:
some_program word1 word2 word3

wówczas:

$0 would contain "some_program"
$1 would contain "word1"
$2 would contain "word2"
$3 would contain "word3"
  • wypróbuj skrypt
#!/bin/bash

echo "Positional Parameters"
echo '$0 = ' $0
echo '$1 = ' $1
echo '$2 = ' $2
echo '$3 = ' $3
  • Sprawdzanie czy parametry podane:
#!/bin/bash

if [ "$1" != "" ]; then
    echo "Positional parameter 1 contains something"
else
    echo "Positional parameter 1 is empty"
fi

lub

#!/bin/bash

if [ $# -gt 0 ]; then
    echo "Your command line contains $# arguments"
else
    echo "Your command line contains no arguments"
fi
  • Przykład
interactive=
filename=~/sysinfo_page.html

while [ "$1" != "" ]; do
    case $1 in
        -f | --file )           shift
                                filename=$1
                                ;;
        -i | --interactive )    interactive=1
                                ;;
        -h | --help )           usage
                                 exit
                                ;;
        * )                     usage
                                exit 1
    esac
    shift
done
  • shift jest wbudowanym poleceniem, które działa na parametrach. Za każdym razem, gdy wywołujesz shift, "przesuwa" ono wszystkie parametry o jeden. $2 staje się $1, $3 staje się $2, $4 staje się $3, itd.

Pętla for

  • Przykład 1
#!/bin/bash

for i in word1 word2 word3; do
    echo $i
done
  • Przykład 2
#!/bin/bash

count=0
for i in $(cat ~/.bash_profile); do
    count=$((count + 1))
    echo "Word $count ($i) contains $(echo -n $i | wc -c) characters"
done
  • Przykład 3 ($@ zawiera listę argumentów skryptu)
#!/bin/bash

for i in "$@"; do
    echo $i 
done
  • Przykład 4
#!/bin/bash

for filename in "$@"; do
    result=
    if [ -f "$filename" ]; then
        result="$filename is a regular file"
    else
        if [ -d "$filename" ]; then
            result="$filename is a directory"
        fi
    fi
    if [ -w "$filename" ]; then
        result="$result and it is writable"
    else
        result="$result and it is not writable"
    fi
    echo "$result"
done
  • Przykład 5
#!/bin/bash

# cmp_dir - program to compare two directories

# Check for required arguments
if [ $# -ne 2 ]; then
    echo "usage: $0 directory_1 directory_2" 1>&2
    exit 1
fi

# Make sure both arguments are directories
if [ ! -d $1 ]; then
    echo "$1 is not a directory!" 1>&2
    exit 1
fi

if [ ! -d $2 ]; then
    echo "$2 is not a directory!" 1>&2
    exit 1
fi

# Process each file in directory_1, comparing it to directory_2
missing=0
for filename in $1/*; do
    fn=$(basename "$filename")
    if [ -f "$filename" ]; then
        if [ ! -f "$2/$fn" ]; then
            echo "$fn is missing from $2"
            missing=$((missing + 1))
         fi
    fi 
done
echo "$missing files missing"

Tablice w bash

  • Możliwe jest tworzenie zmiennych tablicowych:
var=(war1 wart2 war2 warn)
  • Przykład
#!/bin/bash

tablica=(e1 e2 e3)

echo ${tablica[0]}
echo ${tablica[1]}
echo ${tablica[2]}
# wypisz wszystkie elementy tablicy
echo ${tablica[*]}

# wypisz liczbę znaków z jakich składa się pierwszy element tablicy:
echo ${#tablica[0]}
# wypisz liczbę elementów tablicy:
echo ${#tablica[@]}
 echo ${#tablica[*]}

#dodawanie elementów
tablica[3]=el4
  • Aby usuną element z tablicy używa się polcenia unset
unset tablica[2]

Przykładowe skrypty