printf and Here Documents
Prerequisites: Redirection: sending output to files
printf: precise output
echo is fine for simple messages, but its options vary between systems.
printf formats output precisely and portably:
printf "Hello, %s!\n" "Ada"
printf "%-10s|%5d|%8.2f\n" "keyboard" 3 89.5
printf "%-10s|%5d|%8.2f\n" "monitor" 12 249.99
printf "%s\n" apple banana cherry
printf "%03d\n" 7
Hello, Ada!
keyboard | 3| 89.50
monitor | 12| 249.99
apple
banana
cherry
007
%stext,%dinteger,%fdecimal (%.2fwith two places),%%a literal percent sign.- A number sets the width;
-left-aligns. \nmust be written explicitly —printfdoesn't add a newline.- If there are more arguments than placeholders, the format is reused
— which is how
printf "%s\n" a b cprints one per line.
Here documents
A here document feeds multi-line text into a command:
name="Ada"
cat <<EOF
Dear $name,
Your order total is \$120.
EOF
cat <<'EOF'
Variables like $name are NOT expanded here.
EOF
Dear Ada,
Your order total is $120.
Variables like $name are NOT expanded here.
- With
<<EOF, variables and$(...)are expanded. - With
<<'EOF'(quoted), the text is taken literally — ideal for writing scripts or config files that contain$. <<-EOFstrips leading tab characters, so the text can be indented inside functions.
Generating files
service="api"
port=8080
cat > "$service.conf" <<EOF
[$service]
listen = 0.0.0.0:$port
workers = $(( 2 * 2 ))
EOF
cat api.conf
[api]
listen = 0.0.0.0:8080
workers = 4
Here strings
<<< passes a single string as input:
wc -w <<< "how many words are here"
tr 'a-z' 'A-Z' <<< "shout"
5
SHOUT