Rady na webu:

https://www.root.cz/clanky/programovani-v-bash-shellu/

https://www.fi.muni.cz/usr/brandejs/P004/

 

#<------------------------------- skript lze spoustet dvěma způsoby ------------------------------->#

## 1) zadáme ./skript.sh (v top pripade ale MUSI byt v souboru shebang)
## 2) zadáme bash skript.sh (v tomto pripade se skript spusti i kdyz tam nebude shebang nebo neni soubor spustitelny)

## #!/bin/bash <===> shebang - toto musi byt bezpodminecne na prvnim radku, skript se spousti ./skript.sh
## sharp (#) and bang (!)
## sudo chmod +x skript.sh <===> pridam pravo spoustet skript {skript.sh} NUTNE aby script bezel

## Why not simply invoke the script with scriptname? If the directory you are in ($PWD) is where scriptname is located, why doesn't this work? This fails because, for security reasons, the current directory (./) is not by default included in a user's $PATH. It is therefore necessary to explicitly invoke the script in the current directory with a ./scriptname.

#<------------------------------------ ------------------------------------>#

## text="Ahoj", pokud chceme přistupovat k hodnotě proměnné musíme zadávat $text.
## kdo=$(whoami)
## prikaz done ukoncuje syntaxy do, tedy par do, done, pouziva se u for
## Shell comparison example: [ 100 -eq 50 ]; echo $? [ "GNU" = "UNIX" ]; echo $?
## Ensure whitespaces between the brackets and the actual check/comparison statement. For example, the following will not work. if [$x==0]
## Ujistete se ze jsou mezi zavorkama a hodnotama mezery / skript by jinak nebezel There must be a space between the [ and the variable name and the equality operator ==. If you miss any of the spaces here, you’ll see an error like ‘unary operator expected’ or missing `]’.
## Never name your private variables using UPPERCASE characters. This is because uppercase variable names are reserved for internal shell variables, and you run a risk of overwriting them. This may lead to the dysfunctional or misbehaving script execution
## Komentare pridame dvema zpusoby:
## 1) napiseme znak # tj. jednoradkovy komentar nebo
## 2) viceradkovy komentar napiseme dvojtecku mezeru a dva apostrofy : 'tento koment muze mit vice radku'

## to force numbers with leading zeros into decimals: 10#$number so number=09; echo "$((10#$number))" will output 9 while echo $((number)) will produce a "value too great for base" error.

#<------------------------------- apostrofy, uvozovky atd. ------------------------------->#

"ret" Normální uvozovky. Řetězec uvnitř těchto uvozovek je chápán shellem literárně (obyčejný text). To znamená, že různé metaznaky jsou ignorovány (středník neznamená konec příkazu, ale prostě středník). Do textu jsou vkládány hodnoty proměnných.

text=10; echo "text je $text;" # vytiskne: text je 10;

'ret' Apostrof vedle klávesy enter. Řetězec uvnitř těchto apostrofů je chápán shellem literárně (obyčejný text). Na rozdíl od normálních uvozovek je navíc zamezeno nahrazování proměnných jejich hodnotou.

text=10; echo 'text je $text;' # vytiskne: text je $text;

`ret` Obrácené apostrofy. Řetězec je shellem chápán jako příkaz k vykonání; Tento řetězec je vykonán před zpracováváním zbytku řádku a výsledek příkazu nahradí původní řetězec  `ret`

text=whoami; echo `$text;` # v mem pripade vytiskne: chicky

 

#<------------------------------- READ ------------------------------->#

read promenna <===> ceka na vstup od uzivatele a prida ho do promene promenna - k te se pak pristuje pomoci $promenna
read foo -p <===> kurzor na vstupu bude blikat na stejny radce / read -p "Vepiš svý jméno:" name
read foo -s <===> vypisovane udaje inputu budou neviditelne - vhodne u hesel#
read foo -a <===> vepsane udaje v inputu ulozi do ARRAY pole a muzem ho pak vyvolat ${foo[n]} kde n je pozice v poli

#<------------------------------------ ------------------------------------>#

$0 <===> nultý poziční parametr, tedy parametr předcházející tomu prvnímu.Program tak může snadno zjistit, jakým způsobem byl spuštěn a jak se vlastně jmenuje. // vypíse název souboru (skriptu) ze ktereho je spusten tento skript / The name of the Bash script.
$1 <===> Vypíše první parametr = "./skript.sh parametr1" vypíše parametr1
$2 <===> Vypíše druhý parametr = "./skript.sh parametr1 parametr2" vypíše parametr2
$@ <===> zobrazí seznam všech pozičních parametrů oddelenych mezerou ......vypise vsechny argumnety / All the arguments supplied to the Bash script.
$* <===> zobrazí seznam všech pozičních parametrů oddělených předdefinovatelným oddělovačem.... Vypíše všechny parametry = "./skript.sh parametr1 parametr2" vypíše parametr1 parametr2
$# <===> vypise pocet argumentu v poli# /How many arguments were passed to the Bash script
$? <===> Vypíše návratový kód posledního procesu / The exit status of the most recently run process.
$$ <===> Vypíše PID skriptu / The process ID of the current script.
$1 - $9 <===> do promenych 1 az 9 ulozi argumenty napsane za skriptem oddelene mezerou / The first 9 arguments to the Bash script. (As mentioned above.)
${10} <===> pozicni parametr 10 a vice musime zadavat v zavorkach
argumenty=("$@") <===> pokud skript spustime s argumenty (napr. heloworld.sh jedna dve tri ctyri) tak tyto promenne se ulozi do pole
unset PROMENNA <===> vyprazdni promennou PROMENNA takze nebude uz prirazena
grep '#' test4.sh <===> vypise jen radku ktere zacinaji/nebo obsahuji symbol #
$USER <===> The username of the user running the script./jméno uživatele
$HOSTNAME <===> The hostname of the machine the script is running on./jméno počítače
$SECONDS <===> The number of seconds since the script was started./počet sekund od startu shellu
$RANDOM <===> Returns a different random number each time is it referred to./náhodné číslo do 0 do 32767
$LINENO <===> Returns the current line number in the Bash script.
$BASH_VERSION <===> verze interpretru Bash
$GROUPS <===> seznam skupin, jichž je současný uživatel členem
$HISTSIZE <===> počet zadaných příkazů, které si Bash pamatuje
$HOME <===> domovský adresář
$HOSTTYPE <===> typ počítače
$MAIL <===> soubor s lokální schránkou
$OLDPWD <===> předchozí pracovní adresář
$OSTYPE <===> typ operačního systému
$PWD <===> aktuální pracovní adresář
$SHELL <===> určuje výchozí interpretr
$TMP <===> dočasný adresář


sleep 5 <===> skript pocka 5 sec nez se spusti
echo <===> v radku ciste bez argumentu vytvori prazdny radek / dobre na oddelovani vypisu.
echo -e "Ahoj \nsvete" <===> volba -e zpusobi, ze se vystup rozdeli na novou radku (diky \n)
echo -e "\tAhoj svete" <===> volba -e zpusobi, ze se vystup posune od zacatku radku osirku tabulatoru (diky \t)


#<------------------------------- POROVNAVANI ------------------------------->#

#Description Numeric Comparison String Comparison
#less than -lt <
#greater than -gt >
#equal -eq =
#not equal -ne !=
#less or equal -le N/A
#greater or equal -ge N/A

 

#<------------------------------- POROVNAVANI 2 ------------------------------->#

#!/bin/bash

VAR1="Linuxize"
VAR2="Linuxize"

if [ "$VAR1" = "$VAR2" ]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi

#<------------------------------- POROVNAVANI 3 ------------------------------->#


#!/bin/bash

read -p "Enter first string: " VAR1
read -p "Enter second string: " VAR2

if [[ "$VAR1" == "$VAR2" ]]; then
echo "Strings are equal."
else
echo "Strings are not equal."
fi


#<------------------------------- How to redirect output of multiple commands to one file ------------------------------->#

## pokud chceme vice prikazu udelat najednou a CELE to zapsat do souboru jsou tri zpusoby:


ssh host tail -f /some/file | awk ..... > /some/file &
ssh host tail -f /some/file | grep .... >> /some/file &

nebo

{
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &
} > /some/file

nebo

exec > /some/file
ssh host tail -f /some/file | awk ..... &
ssh host tail -f /some/file | grep .... &

#<------------------------------------ ------------------------------------>#

hello="A B C D"
echo $hello # A B C D
echo "$hello" # A B C D
# As we see, echo $hello and echo "$hello" give different results.


#<------------------------------- FILE COMPARASION ------------------------------->#

# Parameters used for file comparison are

-d file <===> Checks if file exists and is a directory
-e file <===> Checks if file exists
-f file <===> Checks if file exists and is a file
-r file <===> Checks if file exists and is readable
-s file <===> Checks if file exists and is not empty
-w file <===> Checks if file exists and is writable
-x file <===> Checks if file exists and is executable
-O file <===> Checks if file exists and is owned by the current user
-G file <===> Checks if file exists and the default group is the same as the current user
file1 -nt file2 <===> Checks if file1 is newer than file2
file1 -ot file2 <===> Checks if file1 is older than file2


#<------------------------------------ ------------------------------------>#


# Example of using if statement:
if [ -e $input_file ]; then
echo "The input file exists."
else
echo "The input file does not exist."
fi
#<------------------------------------ ------------------------------------>#

# Check if a file exists in a directory
if test -e "/home/fosslinux/Documents/my backups/syslog_2.txt"; then
echo "The file exists."
else
echo "The file does not exist."
fi
#<------------------------------- SPOJENI PRIKAZU NA JEDNE RADCE ------------------------------->#

echo hello; echo there <===> vypise oba prikazy postupne / za strednikem musi byt mezera

#<------------------------------- spojovani promennych ------------------------------->#

p1=ahoj
p2=cau
echo "${p1}tato${p2}mamo"

#nebo

var=$var1$var2

#nebo

var="$var1 - $var2"

 


Context | Expression | Result (value of c)
--------------------------------------+-----------------------+---------------------
Two variables | c=$a$b | helloworld
A variable and a literal | c=${a}_world | hello_world
A variable and a literal | c=$1world | oneworld
A variable and a literal | c=$a/world | hello/world
A variable, a literal, with a space | c=${a}" world" | hello world
A more complex expression | c="${a}_one|${b}_2" | hello_one|world_2
Using += operator (Bash 3.1 or later) | c=$a; c+=$b | helloworld
Append literal with += | c=$a; c+=" world" | hello world

#<------------------------------- LOOPS / SMYCKY ------------------------------->#

## LOOPS / SMYCKY se deli na tri druhy: for, while a until

#<------------------------------- FOR ------------------------------->#

for (( a=1 ; $a-4 ; a=$a+1 ))
do echo $a
done

#<------------------------------------ ------------------------------------>#
#!/bin/bash
for item in [list]
do
[commands]
done
#<------------------------------------ ------------------------------------>#

for i in $(cat list.txt); do touch $i; done

#<------------------------------------ ------------------------------------>#

# Example of using for loop:
for file in *.txt; do
echo "Processing file: $file"
done

#<------------------------------------ ------------------------------------>#

# Initialize counter variable
file_count=0

# Loop through all files in directory and count them
for file in "/home/fosslinux/Documents/my backups/"*; do
if [ -f "$file" ]; then
file_count=$((file_count+1))
echo "$file"
fi
done

# Display a message indicating the total number of files
echo "There are $file_count files in this directory."

#<------------------------------------ ------------------------------------>#


for days in Monday Tuesday Wednesday Thursday Friday Saturday Sunday
do
echo “Day: $days”
done

#<------------------------------- PRIRAZENI NAZVU SOUBORU ------------------------------->#

## zdroj - slozka kde jsou puvodni soubory s delsimi nazvy
## cil - slozka, kde jsou vyexportovane PDF ale maji nove nazvy a ty prave potrebuji pojmenovat nazvama souboru ze slozky "zdroj"

## vytvorim seznam puvodnich nazvu souboru
cd /tmp/zdroj
ls *.pdf > seznam

## presunu seznam o level vys
mv seznam ..

## presunu se do cilove slozky
cd ../cil

## spustim skriptik ktery da exportovanym PDF [001.pdf, 002.pdf, 003.pdf...] puvodni nazvy ze slozky zdroj [CLB3251.pdf, P0072.pdf, V1946.pdf…]
for file in *.pdf; do read line; mv -v /tmp/cil/"${file}" "${line}"; done < /tmp/seznam

 

#<------------------------------- for vypis ze souboru po radkach ------------------------------->#

soubor="mesice.txt"

cat $soubor | while read line
do
echo $line
done

#<------------------------------- PREJMENOVANI SOUBORU DLE SEZNAMU ------------------------------->#

for file in *.pdf; do read line; mv -v /tmp/cil/"${file}" "${line}"; done < /tmp/seznam

 

#<------------------------------- for MUSIM JESTE VYZKOUSET CO TO DELA ------------------------------->#

echo "Printing files..."
FILES=(/Bash/sample/*) # create an array.
# Works with filenames containing spaces.
# String variable does not work for that case.

for f in "${FILES[@]}" # iterate over the array.
do
echo "this is $f"
done

 

#<------------------------------- WHILE ------------------------------->#

while ( PODMINKA ) {
AKCE
}
#<------------------------------------ ------------------------------------>#


while [condition]
do
[commands]
done

#<------------------------------------ ------------------------------------>#

i=0
while [ $i -le 5 ]
do
echo $i
((i++))
done

#<------------------------------- UNTIL ------------------------------->#


i=0
until [ $i -gt 5 ]
do
echo $i
((i++))
done


#<------------------------------- ARGUMENTY ------------------------------->#

echo
echo "# arguments called with ----> ${@} "
echo "# \$1 ----------------------> $1 "
echo "# \$2 ----------------------> $2 "
echo "# path to me ---------------> ${0} "
echo "# parent path --------------> ${0%/*} "
echo "# my name ------------------> ${0##*/} "
echo
exit

#<------------------------------------ ------------------------------------>#


# Notice on the next line, the first argument is called within double, and single quotes, since it contains two words

$ /misc/shell_scripts/check_root/show_parms.sh "'hello there'" "'william'"

#<------------------------------------ ------------------------------------>#


# arguments called with ---> 'hello there' 'william'
# $1 ----------------------> 'hello there'
# $2 ----------------------> 'william'
# path to me --------------> /misc/shell_scripts/check_root/show_parms.sh
# parent path -------------> /misc/shell_scripts/check_root
# my name -----------------> show_parms.sh


#<------------------------------- definice promennych ------------------------------->#

Pro definici proměnné v Linuxu používáme následující formát: proměnná=hodnota.
Pokud bychom například chtěli uložit aktuální adresář do proměnné s názvem „aktuální_adresář“, zapsali bychom
current_addr=$(pwd). Pro přístup k hodnotě proměnné používáme symbol dolaru následovaný
názvem proměnné, jako např $current_dir.

#<------------------------------- cyklus for in ------------------------------->#

for a in A B C D
do echo $a
done

#<------------------------------- if ------------------------------->#


# Example of using exit code and error message:
if [ ! -e $input_file ]; then
echo "Error: input file does not exist."
exit 1
fi

#<------------------------------------ ------------------------------------>#

if [ $(whoami) = 'root' ]; then
echo "You are root"
fi

#<------------------------------------ ------------------------------------>#

echo “Enter a number”
read a #The user input in this command line will be stored as variable a
b=50 #The value of variable b
if [[$a -eq $b]]
then
echo “Same number”
else
echo “Different number”
fi

#<------------------------------------ ------------------------------------>#


a=2462620
b=2462620

if [ "$a" -eq "$b" ]; then
echo "They're equal";
fi

#nebo

a=2.00
b=1

if (( $(bc <<<"$a > $b") )); then
echo "a is greater than b"
else
echo "a is not greater than b"
fi

#<------------------------------- if-else ------------------------------->#

if [ $(whoami) = 'root' ]; then
echo "You are root"
else
echo "You are not root"
fi


#<------------------------------------ ------------------------------------>#


# Using file comparison
dir=/home/dan
if [ -d $dir ]
then
echo "$dir is a directory"
cd $dir
ls -a
else
echo "$dir is not a directory"
fi


#<------------------------------- if-else 2 ------------------------------->#


if PODMINKA
then
PRIKAZ_1
else
PRIKAZ_2
fi

#<------------------------------------ ------------------------------------>#
if (PODMINKA1){
AKCE1
}
else if (PODMINKA2){
AKCE2
}
else{
AKCE3
}

#<------------------------------- if-else_if-else ------------------------------->#

if PODMINKA_1
then
PRIKAZ_1
elif PODMINKA_2
then
PRIKAZ_2
else
PRIKAZ_3
fi

#<------------------------------------ ------------------------------------>#

if PODMINKA_1
then
if PODMINKA_2
then
PRIKAZ_1
else
PRIKAZ_2
fi
else
PRIKAZ_3
fi

#<------------------------------- Functions 1 ------------------------------->#

## prvni zpusob:

function_name () {
first command
second command
}


## nebo pokud chcete psat v jednom radku

function_name () { first command; second command; }

#<------------------------------- Functions 2 ------------------------------->#

## druhy zpusob:

function function_name {
first command
second command
}

## nebo pokud chcete psat v jednom radku

function function_name { first command; second command; }

#<------------------------------------ ------------------------------------>#