Bash Trénink
Regulární výrazy pomocí [[...]]
$ string=whatever
$ [[ $string =~ h[aeiou] ]]
$ echo $?
0
Evaluace aritmetického výrazu pomocí ((...))
Možno potom zkombinovat s and příkazem
((verbose)) && command ## execute command if verbose != 0
Tests
-f test regular file
-e file exists
-d directory exists
-h symbolic link
-x execute file
-s is file and is not empty
mozno i negovat pomocí ! -f
-z arguments are empty
-n arguments are nonempty
conditional operators
if
if ... then elif then fi
if [ -d "$dir" ] && cd "$dir"
then
echo "$PWD"
fi
Case
case WORD in
PATTERN) COMMANDS ;;
PATTERN) COMMANDS ;; ## optional
esac
Listing 3-4. Does One String Contain Another?
case $1 in
*"$2"*) true ;;
*) false ;;
esac
Listing 3-5. Is This a Valid Positive Integer?
case $1 in
*[!0-9]*) false;;
*) true ;;
esac
Check appropriate count of input arguments
case $# in
3) ;; ## We need 3 args, so do nothing
*) printf "%s\n" "Please provide three names" >&2
exit 1
;;
esac
Looping
while
while <list>
do
<list>
done
until
n=1
until [ $n -gt 10 ]
do
echo "$n"
n=$(( $n + 1 ))
done
for
for var in Canada USA Mexico
do
printf "%s\n" "$var"
done
Command Substitution
wc -l $( date +%Y-%m-%d ).log
Vypise pocet radek v danem souboru 2017-03-09.log
Process Substitution
Vytvari docasny soubor pro prikaz nebo list prikazu.
Lze jej uzit potom kdekoliv se pouziva soubor
while read perms links owner group size month day time file
do
printf "%10d %s\n" "$size" "$file"
totalsize=$(( ${totalsize:=0} + ${size:-0} ))
done < <(ls -l *)
echo ${totalsize-unset}
12879
Check if variable x is set
if [[ ${x+X} = X ]] ## If $x is set
unset x ## unset variable x
export x ## exportuje promennou x do environment variables
Opakování pomocí čárek
printf "%s\n" ${RANDOM}{,,,,,}
printf "%s\n" {1..5}{,} ## dvojice 1122334455
Poslední pipe bude provedena v current shellu (bash 4.2)
shopt -s lastpipe
Ověření verze bash skriptu
case $BASH_VERSION in
[12].*) echo "You need at least bash3.0 to run this script" >&2; exit 2;;
esac
${var:-default} and ${var-default}: Use Default Values
The most commonly used expansion, ${var:-default}, checks to see whether a variable is unset or empty
and expands to a default string if it is:
$ var=
$ ba "${var:-default}" ## The sa script was introduced in Chapter 4
:default:
If the colon is omitted, the expansion checks only whether the variable is unset:
$ var=
$ ba "${var-default}" ## var is set, so expands to nothing
::
$ unset var
$ ba "${var-default}" ## var is unset, so expands to "default"
:default:
defaultfile=$HOME/.bashrc
## parse options here
filename=${filename:-"$defaultfile"}
${var:+alternate}, ${var+alternate}: Use Alternate Values
The complement to the previous expansion substitutes an alternate value if the parameter is not empty or,
without a colon, if it is set. The first expansion will use alternate only if $var is set and is not empty.
To prevent the leading space, you can use parameter expansion:
$ var=
$ for n in a b c d e f g
> do
>
var="${var:+"$var "}$n"
> done
$ ba "$var"
:a b c d e f g:
another solution:
[ -n "$var" ] && var="$var $n" || var=$n
${var:?message}, ${var?message}: Display Error Message If Empty or Unset
If var is empty or not set, message will be printed to the standard error, and the script will exit with a status
of 1. If message is empty, parameter null or not set will be printed. Listing 5-2 expects two non-null
command-line arguments and uses this expansion to display error messages when they are missing or null.
Listing 5-2. checkarg, Exit If Parameters Are Unset or Empty
## Check for unset arguments
: ${1?An argument is required} \
${2?Two arguments are required}
## Check for empty arguments
: ${1:?A non-empty argument is required} \
${2:?Two non-empty arguments are required}
echo "Thank you."
Ostatní viz dokumentace pdf...
${var##PATTERN}: Remove the Longest Match from the Beginning
The variable is expanded, and the longest string that matches PATTERN is removed from the beginning of the
expanded value. This is often used to extract the name of a script from the $0 parameter, which contains the
full path to the script:
scriptname=${0##*/} ## /home/chris/bin/script => script
${var:OFFSET:LENGTH}: Return a Substring of $var
A substring of $var starting at OFFSET is returned. If LENGTH is specified, that number of characters is
substituted; otherwise, the rest of the string is returned. The first character is at offset 0:
$ var=Toronto
$ sa "${var:3:2}"
:on:
$ sa "${var:3}"
:onto:
${!var}: Indirect Reference
If you have one variable containing the name of another, for example x=yes and a=x, bash can use an
indirect reference:
$ x=yes
$ a=x
$ sa "${!a}"
:yes:
The same effect can be had using the eval builtin command, which expands its arguments and
executes the resulting string as a command:
$ eval "sa \$$a"
:yes:
${var^PATTERN}: Convert to Uppercase
$ var=toronto
$ sa "${var^}"
:Toronto:
$ sa "${var^^}"
:TORONTO:
${var,PATTERN}: Convert to Lowercase
This expansion works in the same way as the previous one, except that it converts uppercase to lowercase:
$ var=TORONTO
$ sa "${var,,}"
:toronto:
$ sa "${var,,[N-Q]}"
:ToRonTo:There is also an undocumented expansion that inverts the case:
$ var=Toronto
$ sa "${var~}"
:toronto:
$ sa "${var~~}"
:tORONTO:
Cyklovani pres vstupni positional parameters
for param in "$@" ## or just: for param
do
: do something with $param
done
And this is the second:
while (( $# ))
do
: do something with $1
shift
done
Arrays
$ printf "%s\n" "${BASH_VERSINFO[*]}"
4 3 30 1 release i686-pc-linux-gnuoldld
$ printf "%s\n" "${BASH_VERSINFO[@]}"
4
3
30
1
release
i686-pc-linux-gnu
Various parameter expansions work on arrays; for example, to get the second and third elements from
an array, use this:
$ printf "%s\n" "${BASH_VERSINFO[@]:1:2}" ## minor version number and patch level
3
30
The length expansion returns the number of elements in the array when the subscript is * or @, and it
returns the length of an individual element if a numeric index is given:
$ printf "%s\n" "${#BASH_VERSINFO[*]}"
6
$ printf "%s\n" "${#BASH_VERSINFO[2]}" "${#BASH_VERSINFO[5]}"
2
17
Přiřazení hodnot do pole a použití postupně inkrementujícího indexu pole
$ unset a
$ a[${#a[@]}]="1 $RANDOM"
$ a[${#a[@]}]="2 $RANDOM"
$ a[${#a[@]}]="3 $RANDOM"
$ a[${#a[@]}]="4 $RANDOM"
$ printf "%s\n" "${a[@]}"
1 6007
2 3784
3 32330
4 25914
$ province=( Quebec Ontario Manitoba )
$ printf "%s\n" "${province[@]}"
Quebec
Ontario
Manitoba
$ province+=( Saskatchewan )
$ province+=( Alberta "British Columbia" "Nova Scotia" )
$ printf "%-25s %-25s %s\n" "${province[@]}"
Quebec Ontario Manitoba
Saskatchewan Alberta British Columbia
Nova Scotia
Associative Arrays
Associative arrays, introduced in bash in version 4.0, use strings as subscripts and must be declared before
being used:
$ declare -A array
$ for subscript in a b c d e
> do
> array[$subscript]="$subscript $RANDOM"
> done
$ printf ":%s:\n" "${array["c"]}" ## print one element
:c 1574:
$ printf ":%s:\n" "${array[@]}" ## print the entire array
:a 13856:
:b 6235: