The shell and running commands

Bash · Essentials · 8 min

Every other shell skill builds on reading and typing command lines correctly.

A shell is a program that reads command lines, finds the programs they name and runs them. Bash is the default shell on most Linux distributions and the usual language of .sh scripts. When you open a terminal you get a prompt; you type a line and press Enter.

Bash splits the line into words on spaces and tabs. The first word is the command, the rest are its arguments. By convention short options look like -l, long ones like --all, and short ones can often be bundled (ls -la). Separate several commands on one line with ;, and start a comment with #.

A command can be one of several kinds, and type tells you which:

  • a builtin such as cd or echo, implemented inside bash itself,
  • an alias or function you or your config defined,
  • an external program found by searching the directories in $PATH.

For help, use help name for builtins and man name (or name --help) for programs. Interactive conveniences pay off quickly: Tab completes commands and file names, Up/Down walk through history, Ctrl-R searches it, Ctrl-C interrupts the running command and Ctrl-L clears the screen.

Example

echo hello   world          # hello world   (extra spaces just separate words)
type cd                     # cd is a shell builtin
type ls                     # ls is /usr/bin/ls   (or an alias, interactively)
echo "$BASH_VERSION"        # 5.2.21(1)-release
help echo | head -n 1       # echo: echo [-neE] [arg ...]
ls -la /tmp | head -n 2     # bundled short options
date; pwd                   # two commands on one line
# everything after # is a comment

Remember

  • Command line = command word + arguments, split on whitespace
  • type tells you if a name is a builtin, alias, function or program
  • help for builtins, man or --help for programs

Watch out for

  • Expecting several spaces between arguments to be kept: unquoted whitespace only separates words.

Check yourself

  1. Which command tells you whether cd is a builtin or a program on disk?
  2. How many arguments does `ls -l /tmp /var` pass to ls?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.gnu.org/software/bash/manual/bash.html#Simple-Commands