run.shCourse
Shell
A variable that holds text, then quoting, then why a number is still text, a function, local scope, and the exit code.
- itemtextlatte
6 lessons, in orderFree to read
Syllabus
Basics
The types, explained, then an object you can name and call.
-
01
Shell from zero: a variable holds text
2 min read
A shell variable holds text. item=latte stores latte, and echo prints it. There are no spaces around the equals sign.
item=latte echo "$item"latte -
02
Shell from zero: quote the expansion
2 min read
A value with a space splits into two words if you leave the quotes off. "$name" keeps it one value. The program prints oat latte.
Builds on lesson 1.
name="oat latte" echo "$name"oat latte
Practice
A rule that prevents a bug, then a program that uses the object.
-
03
A variable that looks like a number is text. $((cents * 2)) evaluates it as arithmetic. The program stores 450 and prints 900.
Builds on lessons 1 through 2.
cents=450 echo $((cents * 2))900 -
04
A function packages a command you want to repeat. label prints a drink and its price. The program prints latte $4.50.
Builds on lessons 1 through 3.
label() { printf '%s $%d.%02d\n' "$1" $(($2 / 100)) $(($2 % 100)) } label latte 450latte $4.50
Further
One more idea, then a program that puts the pieces together.
-
05
Shell from zero: local keeps the name inside
2 min read
local makes a variable private to the function. The function prints muffin. The script then prints latte. The caller's drink is unchanged.
Builds on lessons 1 through 4.
name=latte inner() { local name=muffin echo "$name" } inner echo "$name"muffin latte -
06
Shell from zero: read the exit code
2 min read
A command returns a number when it finishes. 0 means it worked. An empty drink name fails test -n. The program prints 1. Check the code before you trust the result.
Builds on lessons 1 through 5.
name="" test -n "$name" echo $?1
Readings
Shorter pieces in the same language. Any order is fine once the lessons feel familiar.
-
jq: a pipeline for JSON
2 min
GoByte Skills #24: in jq, bob does not become null. He stops existing. select emits nothing for a miss, because every jq filter takes JSON in and emits a stream of zero or more values, and | runs the next step once per value.
-
xargs -P: parallelism in one flag
2 min
GoByte Skills #23: xargs -P turns a serial loop into a worker pool. Twelve seconds of jobs finish in three. Also: the missing -n that makes -P do nothing at all.
-
Pipes: the concurrency model you already use
2 min
GoByte Skills #22: a pipeline is every stage running at once, joined by 64 KiB buffers. awk streams in 1.6 MB. sort cannot: on a 444 MB log it held 2.1 GB. So filter first.