Bash, lesson 1
Bash is the shell: the program that reads the commands you type in a terminal and runs them. A Bash script is simply a file of those commands, run from top to bottom. Scripts are the everyday glue of Linux and macOS systems, from build steps to backups.
Most scripts start with a shebang line, which tells the system which program should run the file:
echo prints its arguments separated by single spaces, followed by a newline:
echo -n leaves out the final newline, so the next output continues on the same line.
Quoting matters more in Bash than in most languages. Without quotes, Bash splits text into
separate words at whitespace and echo joins them back with one space, so
echo a b prints a b. Double quotes keep the text as one piece, exactly as written:
echo "a b" prints . When in doubt, quote.
2 exercises to try what you just read.
a bSingle quotes are even stricter: everything inside is taken literally, including $, which you
will soon use for variables. echo 'Price: $5' prints Price: $5.
printf gives precise control. Its first argument is a format; %s is replaced by the next
argument as text and %d by a whole number. It does not add a newline unless you write
\n:
A useful quirk: if you give more arguments than the format uses, printf repeats the format
until they are all used:
Because echo behaves slightly differently between systems (especially with -e and
backslashes), many people prefer printf whenever the output format matters.
A # at the start of a word begins a comment that runs to the end of the line. The shebang is
technically a comment too; Bash ignores it, but the operating system reads it.
Bash reads and runs one command at a time. Each command finishes with an exit status: 0
means success, anything else means failure. By default a failing command prints an error and the
script carries on with the next line, which is different from most languages. You will use exit
statuses for decisions in lesson 4.
Write a script that prints exactly these two lines:
The script reads no input.
Print a shopping list with a header line and one item per line, each item preceded by * :
Print the header with echo, and print all three items with one printf call that receives
milk, eggs and bread as separate arguments (let the format repeat).
#!/bin/bash
echo "Hello, World!"echo "Hello, World!"
echo Total: 42 # quotes are optional for simple words
echo # prints an empty lineprintf "Hello, %s!\n" "Ada" # Hello, Ada!
printf "%s scored %d points\n" Ben 42printf "%s\n" apple pear plum # three lines# This is a comment
echo "This runs" # comment after a commandHello, World!
I am learning Bash.Shopping list:
* milk
* eggs
* bread