Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 34Naam in het boek: Strings and Numbers

Work with strings and numbers

Scripts often need to cut text, change file endings, convert case or calculate. bash can do most of this itself with parameter expansion and arithmetic expansion, without starting extra programs like sed or expr. For decimal numbers there is bc.

  • 8 Lessen
  • 3 Commando's
  • 1 Labs

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

34.1

Use basic parameters

$a and ${a} are the same. Braces are needed when text follows, and for parameters from 10 on.

a="foo"
echo "$a_file"
 
echo "${a}_file"
foo_file
echo "${11}"

Commando's in deze les

34.2

Handle empty variables

Four expansions decide what happens when a variable is unset or empty.

ExpansionIf var is unset or emptyOtherwise
${var:-word}Use wordUse the value
${var:=word}Use word and set var=wordUse the value
${var:?word}Print word to stderr and stop the scriptUse the value
${var:+word}Use nothingUse 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 set

Op het werk

port="${PORT:-8080}" gives a default value that the user can change with an environment variable.

Commando's in deze les

34.3

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_VERSION

Commando's in deze les

34.4

Measure, cut and change strings

bash can measure a string, take a part, remove a start or end pattern, and replace text.

ExpansionResult
${#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 taskExpansionExample 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

Onthoud

These expansions are much faster than calling sed, basename or cut in a loop. The book shows a script that runs about 3 times faster after this change.

34.5

Change upper and lower case

declare -u and declare -l force a variable to upper or lower case. ^ and , expansions convert values.

ExpansionResult
${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"
HELLO

Op het werk

Normalize user input before a test: answer="${REPLY,,}", then compare with yes only.

Commando's in deze les

34.6

Calculate with $(( ))

$(( )) works with whole numbers. It knows number bases, all C operators, assignments and logic.

NotationBase
numberDecimal (10)
0numberOctal (8)
0xnumberHexadecimal (16)
base#numberAny base, like 2#11111111
OperatorMeaning
+ - * /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 : expr3If 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.

Commando's in deze les

34.7

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
loan-calc: monthly payment with bc
#!/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"
	EOF
loan-calc 135000 0.0775 180
1270.7222490000

Commando's in deze les

34.8

Summary 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?

Commando's in deze les

Oefenen

Alle commando's in dit hoofdstuk