terminalcount.sh (the script)$ ./count.shfound notes.txtfound todo.txt2 text files$ echo $?01#!/bin/bash2count=03for f in *.txt; do4 count=$((count + 1))5 echo "found $f"6done7echo "$count text files"bashcountfname 1name 2Linux kernelfolderhello.pynotes.txttodo.txt./count.shnotes.txttodo.txt
Back: the terminal and the script. Middle: bash, its variables and the glob's list. Then the kernel and the folderCells: a variable's name above, its value on the frontTokens: the command, a start signal, file names, and envelopes carrying values and outputAt the back, the terminal and the script count.sh. In front of them, the running bash process, its two variables and the list its glob made; then the Linux kernel, and at the front a folder with three files. The kernel reads the shebang and starts bash; bash runs the script line by line: count=0, the glob picks the two .txt files, each pass of the loop sets f, adds one to count and prints a line, and the script ends with exit status 0.

A script

  1. A Bash script is a plain text file of commands. Bash runs them top to bottom, as if you typed each one. This script, count.sh, counts the .txt files in a folder. Make it runnable once with chmod +x count.sh.

Line by line

The end

What happens

;; step 1/9 · script
count.sh   a text file, 7 lines
  bash runs the lines top to bottom
make it runnable (once):
  $ chmod +x count.sh     add execute permission
then run it:
  $ ./count.sh

Some scripts start with #!/usr/bin/env bash instead, which finds bash wherever it is installed. You can also run a script without chmod +x by typing bash count.sh. Bash sorts the names a glob expands to using your locale's order. If no file matches, the pattern stays as it is (the loop would see the text *.txt) unless you turn on shopt -s nullglob.