Bash in 30 lessons
Bash is the shell you type into. A script is a file of the same commands, with variables, conditions and loops.
The 30 lessons
Chapter 1
First steps
Print text, keep values in variables, calculate and read what the user types.
- 1Run a scriptThe first line names the shell.
- 2Keep a value in a variableNo spaces around
=. - 3Read the command line
$1is the first argument,$#is the number of arguments and"$@"is all of them, each whole. - 4Ask the user
read -rpasks and keeps the answer. - 5Use exit codesEvery command ends with a code.
- 6Decide with if
if,elif,elseandfi.
Chapter 2
Decisions and loops
Use conditions to choose what to do and loops to repeat it.
- 7Test files and text
-f,-d,-eand-sask about files,==compares text with a pattern. - 8Choose with case
casecompares a word with patterns;*)takes the rest. - 9Repeat with loops
forgoes over words or counts;whileanduntiltest a condition. - 10Read a file line by line
while readtakes one line per turn andIFScuts it into fields. - 11Count with numbers
$(( ))counts whole numbers. - 12Write functionsA function reads
$1, keeps its nameslocaland gives text back through its output.
Chapter 3
Data, functions and the command line
Keep many values together, write functions and read the command line.
- 13Return a code
returnsets the code thatifand$?read. - 14Keep many valuesAn array keeps its values apart even with spaces;
mapfilereads a file into one. - 15Count with names
declare -Amakes an array with names for its values. - 16Cut text without other commands
#cuts from the front,%from the end,/replaces and,,makes small letters. - 17Join commandsThe sign
|passes the output of one command to the next;$( )puts an output into a text. - 18Steer the output
>writes a new file or replaces the old one,>>adds,2>takes the error output and<<gives a command several lines.
Chapter 4
Files and errors
Read and write files and handle errors such as a missing file.
- 19Write and read a fileWrite with
printfand>, add with>>and read withwhile. - 20Stop at the first error
-eends the script at a failed command,-uat a variable without a value, andpipefailcounts a failure anywhere in a pipe. - 21Clean up at the end
mktemp -dmakes a work folder andtrap EXITremoves it, also after an error. - 22Read options
getoptsreads-l 95and-q;shiftleaves the rest. - 23Build a calculatorA pattern with
=~checks the line andBASH_REMATCHkeeps its parts. - 24Read dfRead the second line of
df -P -kand compare the percentage with a limit.
Chapter 5
Tools for the NAS
Programs that read the state of the NAS and report it.
- 25Find the largest files
findprints the size and path of every file in the folder and its subfolders,sortputs the largest first. - 26Summarise a log
awkcounts by day and level in one pass. - 27Back up a folder with a date
tarpacks the folder, a test reads the archive, and only the newest three stay. - 28Read smartctlThe script reads the output of smartctl -A, marks four error counters above zero and shows the temperature and the days of work.
- 29Build a notepad
mapfileloads the notes into an array,casechoosesadd,listordelete. - 30Finish a toolFunctions read the limit, the volumes, the disks and the log; the report goes to the screen and to
report.txt.
Projects
Longer programs that draw a menu, play a game, greet you at sign-in or show the state of the NAS. Each page shows the screen as the program drew it on a test NAS.
- A framed menu in pure BashA Bash script draws a menu in a double frame, moves a highlighted bar with the arrow keys and opens boxes with the NAS's memory, volumes, uptime and load. You learn cursor moves, colours and key reading without any extra tool.
- A greeting at the SSH loginA Bash script greets you by the time of day and shows the NAS model, uptime, CPU, load, the free space of the data volumes and a tip of the day in one framed banner. You learn to frame text with escapes and how to show it at every SSH login on QTS.
- A live dashboard of the NASA Bash script redraws the CPU, load, temperatures, memory, data volumes and network rates of the NAS every 2 seconds until you press q. You learn to wait for a key with a timeout and to compute a rate from two readings of a counter.
- Blink: a memory game with drive-bay LEDsIn this Bash game the four drive-bay LEDs of a drawn NAS light up in a sequence that grows by one each round, and you repeat it with the keys 1 to 4. You learn timed drawing, seeded random numbers and how to ignore keys typed at the wrong moment.
- Copy a folder with a progress barA Bash script copies a folder block by block and shows a progress bar, the bytes copied, the speed and the time left, with an optional speed limit. You learn traps for Ctrl+C, redrawing lines in place and reading keys while a job runs.
- A backup wizard with dialogA Bash script uses dialog to show a checklist of the NAS's share folders, a confirmation, a progress gauge and a summary of what rsync would copy. You learn dialog's boxes, its colour file and how to feed a gauge from a loop.
Write it
Sign in to the NAS over SSH and type these commands. micro opens an empty file; Ctrl+S saves it and Ctrl+Q closes it.
mkdir -p /share/Public/lessons
cd /share/Public/lessons
micro 29-notepad.shRun it
chmod +x makes the file a program. The words after its name go to the script.
chmod +x 29-notepad.sh
./29-notepad.sh add "Buy two disks"
./29-notepad.sh list