Skip to main content

Shell

A shell is a command-line interpreter that reads your commands, runs them, and shows the output. Bash is the standard shell on most Linux servers, and the shell is also a scripting language for automation.

Understanding the Linux Shell

What Is a Shell in Linux?

The shell is the layer between you and the kernel. When you type ls, the shell parses the line, expands wildcards, variables, and aliases, finds the ls binary through PATH, asks the kernel to run it, and displays the result. Every terminal and SSH session runs a shell.

flowchart TD A[You type a command] --> B[Shell parses and expands] B --> C[Finds binary via PATH] C --> D[Kernel runs it] D --> E[Output shown in terminal]

Which Shell Should I Use?

TEXT
bash Default on most servers. Best for scripting and automation.
sh POSIX shell, sometimes dash. For maximum portability.
zsh Bash-like with richer completion. Popular on workstations and macOS.
fish Friendly interactive shell, not POSIX compatible. Avoid for scripts.
Bash
echo $SHELL # your login shell
echo $0 # the shell you are running now
cat /etc/shells # allowed login shells
chsh -s /bin/zsh # change login shell

Login, Interactive, and Non-Interactive Shells

Which startup files load depends on how the shell starts.

TEXT
Login shell (SSH, su -): /etc/profile then ~/.bash_profile or ~/.profile
Interactive non-login: ~/.bashrc
Non-interactive (scripts,
cron, systemd): no profile files by default, minimal PATH
Bash
# Detect interactive use inside a script
if [ -t 0 ]; then echo "interactive"; else echo "script or pipe"; fi

Troubleshooting the Shell

Symptom Command What to Check
command not found which cmd Not in PATH
Works by hand, fails in cron echo $SHELL in job cron defaults to /bin/sh
Alias missing in script type name Aliases are not inherited
Tip

Use #!/usr/bin/env bash as the shebang so the script finds bash wherever it is installed.

Common Mistake

Forgetting that scripts run by cron do not load .bashrc. Aliases, functions, and PATH tweaks are unavailable, so use absolute paths and set what you need.

Remember

#!/bin/sh does not guarantee bash features. Arrays and [[ ]] need bash.

Frequently Asked Questions

What is the difference between a shell and a terminal?

The terminal is the window that displays text and sends keystrokes. The shell is the program running inside it that interprets your commands.

Why do shell scripts break when run from cron?

cron starts a non-interactive shell, typically /bin/sh, with a minimal PATH and no profile files. Use absolute paths and set variables inside the script.

Why quote variables in shell scripts?

Unquoted variables are split on spaces and expanded as globs, so `rm -rf $DIR` misbehaves if the value has spaces or is empty. Quote as `"$DIR"`.

Found a mistake, an outdated step or a broken link?