Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
$ als gewone gebruiker# als root (of met sudo)
Vaardigheden in dit hoofdstuk
- Tekst wijzigen en rekenen in bash
Use basic parameters
$a and ${a} are the same. Braces are needed when text follows, and for parameters from 10 on.
Handle empty variables
Four expansions decide what happens when a variable is unset or empty.
| Expansion | If var is unset or empty | Otherwise |
|---|---|---|
${var:-word} | Use word | Use the value |
${var:=word} | Use word and set var=word | Use the value |
${var:?word} | Print word to stderr and stop the script | Use the value |
${var:+word} | Use nothing | Use word |
foo=
echo ${foo:-"substitute value if unset"}
substitute value if unset
echo ${foo:="default value if unset"}
default value if unset
echo $foo
default value if unset
foo=
echo ${foo:?"parameter is empty"}
bash: foo: parameter is empty
foo=bar
echo ${foo:+"substitute value if set"}
substitute value if setOp het werk
port="${PORT:-8080}" gives a default value that the user can change with an environment variable.
Find variable names
${!prefix*} lists the names of all variables that start with a prefix.
echo ${!BASH*}
BASH BASH_ARGC BASH_ARGV BASH_COMMAND BASH_LINENO BASH_SOURCE BASH_VERSINFO BASH_VERSIONMeasure, cut and change strings
bash can measure a string, take a part, remove a start or end pattern, and replace text.
| Expansion | Result |
|---|---|
${#var} | Length of the value |
${var:offset} | From position offset to the end (starts at 0) |
${var:offset:length} | length characters from offset |
${var: -5} | The last 5 characters (note the space) |
${var#pattern} | Remove the shortest match from the start |
${var##pattern} | Remove the longest match from the start |
${var%pattern} | Remove the shortest match from the end |
${var%%pattern} | Remove the longest match from the end |
${var/old/new} | Replace the first match |
${var//old/new} | Replace all matches |
${var/#old/new} | Replace only at the start |
${var/%old/new} | Replace only at the end |
foo="This string is long."
echo "'$foo' is ${#foo} characters long."
'This string is long.' is 20 characters long.
echo ${foo:5}
string is long.
echo ${foo:5:6}
string
echo ${foo: -5}
long.
foo=file.txt.zip
echo ${foo#*.}
txt.zip
echo ${foo##*.}
zip
echo ${foo%.*}
file.txt
echo ${foo%%.*}
file
foo=JPG.JPG
echo ${foo/JPG/jpg}
jpg.JPG
echo ${foo//JPG/jpg}
jpg.jpg| Common task | Expansion | Example result |
|---|---|---|
| File name without path | ${path##*/} | /var/log/app.log → app.log |
| Directory of a path | ${path%/*} | /var/log/app.log → /var/log |
| Ending (extension) | ${file##*.} | photo.jpeg → jpeg |
| Name without ending | ${file%.*} | photo.jpeg → photo |
Change upper and lower case
declare -u and declare -l force a variable to upper or lower case. ^ and , expansions convert values.
| Expansion | Result |
|---|---|
${var,,} | All lower case |
${var,} | First character lower case |
${var^^} | All upper case |
${var^} | First character upper case |
foo=aBc
echo "${foo,,} ${foo,} ${foo^^} ${foo^}"
abc aBc ABC ABc
declare -u upper
upper="hello"
echo "$upper"
HELLOOp het werk
Normalize user input before a test: answer="${REPLY,,}", then compare with yes only.
Calculate with $(( ))
$(( )) works with whole numbers. It knows number bases, all C operators, assignments and logic.
| Notation | Base |
|---|---|
number | Decimal (10) |
0number | Octal (8) |
0xnumber | Hexadecimal (16) |
base#number | Any base, like 2#11111111 |
| Operator | Meaning |
|---|---|
+ - * / | Add, subtract, multiply, divide (whole numbers) |
** | Power |
% | Rest (modulo) |
= += -= *= /= %= | Assign |
++ -- | Add / subtract 1 (before or after the variable) |
< <= > >= == != | Compare (1 = true, 0 = false) |
&& || ! | Logic AND, OR, NOT |
expr1 ? expr2 : expr3 | If expr1 then expr2 else expr3 |
<< >> & | ^ ~ | Bit operations |
echo $((0xff))
255
echo $((2#11111111))
255
echo $((5 / 2)) $((5 % 2)) $((2 ** 10))
2 1 1024
foo=1
echo $((foo++)) $foo
1 2
echo $((++foo)) $foo
3 3
for ((i=0; i<8; ++i)); do echo -n "$((1<<i)) "; done; echo
1 2 4 8 16 32 64 128
$ a=0; ((a<1?++a:--a)); echo $a
1- Inside
$(( ))variables do not need$. ((expression))without$only tests or assigns, it prints nothing.
Calculate decimals with bc
bash only knows whole numbers. bc is a calculator language with any precision. scale sets the number of decimals.
echo "5/2" | bc
2
echo "scale=2; 5/2" | bc
2.50
bc <<< "scale=4; 22/7"
3.1428
bc -l <<< "sqrt(2)"
1.41421356237309504880
bc -q
2 + 2
4
quit#!/bin/bash
# loan-calc: calculate monthly loan payments
PROGNAME="${0##*/}"
usage () {
cat <<- EOF
Usage: $PROGNAME PRINCIPAL INTEREST MONTHS
Where:
PRINCIPAL is the amount of the loan.
INTEREST is the APR as a number (7% = 0.07).
MONTHS is the length of the loan's term.
EOF
}
if (($# != 3)); then
usage
exit 1
fi
principal=$1
interest=$2
months=$3
bc <<- EOF
scale = 10
i = $interest / 12
p = $principal
n = $months
a = p * ((i * ((1 + i) ^ n)) / (((1 + i) ^ n) - 1))
print a, "\n"
EOFloan-calc 135000 0.0775 180
1270.7222490000Summary of the chapter
${var:-default}, ${#var}, ${var##*/}, ${var%.*}, ${var//a/b}, ${var^^} and $(( )) do most string and number work inside bash; bc adds decimals.
1Which expansion gives the file name app.log from /var/log/app.log?
${path##*/}.
2How do you use 8080 when the variable PORT is empty?
${PORT:-8080}.
3How do you divide 10 by 3 with 2 decimals?
echo "scale=2; 10/3" | bc (result 3.33).