Running Your First Bash Command

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 12 of 205

A Bash command is a line of text that asks the shell to do one job: print a message, show the date, list files, or start a program. This lesson walks through your first few commands, explains what Bash does between you pressing Enter and seeing the result, and shows how to read the status that every command leaves behind.

Understanding the Concept

Every command you type is a request to run something. When you press Enter, Bash reads the line, splits it into words, and treats the first word as the command name. The remaining words are extra information for that command. Bash then finds the program or built-in feature that matches the name, runs it, and prints whatever the command produces.

When the command ends, Bash also records a number called the exit status. That number tells you whether the command succeeded. You will rely on it heavily when you write scripts.

How Bash Runs a Command

The sequence for one line looks like this:

  1. You type the line and press Enter.
  2. Bash splits the line into words, using spaces as separators.
  3. Bash looks up the first word. It may be a feature built into Bash itself, or a program stored somewhere on disk. Lesson 14 explains the difference.
  4. Bash runs it and passes the other words along.
  5. The output is printed in the terminal.
  6. Bash stores the exit status and shows a new prompt.

In the examples below, the prompt is shown as $ and you type only the text after it.

Your First Command: echo

The echo command prints the words you give it:

echo Hello

Output:

Hello

Here echo is the command name and Hello is the information you pass to it. The output appears on the next line, and then Bash shows a new prompt.

To print a sentence with punctuation or several spaces, put the text in quotes:

echo "Hello,   World"

Output:

Hello,   World

The quotes tell Bash to treat everything between them as one piece of text. Without quotes, Bash splits the line at the spaces, so extra spaces are lost:

echo Hello,   World

Output:

Hello, World

Quoting is covered in detail in a later section, but you can already see why it matters.

Asking the System Questions

Many short commands report facts about your system. Each one runs and prints its result:

whoami

Sample output:

student

whoami prints the name of the user running the shell.

pwd

Sample output:

/home/student

pwd stands for "print working directory". It shows the directory the shell is currently in.

date

Sample output:

Thu Nov 20 10:52:07 UTC 2026

date prints the current date and time as your system sees it. The date format depends on your language settings. You can ask for a specific format by adding a pattern that starts with +:

date +%Y-%m-%d

Sample output:

2026-11-20

Here %Y means the four-digit year, %m the month, and %d the day of the month.

uname -s

Output on Linux:

Linux

uname -s prints the name of the operating system kernel. On macOS the answer is Darwin.

Your output differs from the samples because it depends on your user name, directory, and clock. That is expected.

Listing Files with ls

The ls command lists the files and directories in the current directory:

ls

Sample output in a directory with two files:

notes.txt  report.txt

If the directory is empty, ls prints nothing and returns directly to the prompt. Empty output is not an error.

Doing Arithmetic

Bash can calculate integers with a feature called arithmetic expansion, written $(( )):

echo $((2 + 3 * 4))

Output:

14

Bash evaluates the expression inside the double parentheses using normal operator precedence, so the multiplication happens before the addition. It replaces the whole $((...)) with the result, and echo prints it. The details of arithmetic come later in the tutorial.

Formatting Output with printf

The printf command prints text using a template, which gives you more control than echo:

printf 'Name: %s, Age: %d\n' Asha 30

Output:

Name: Asha, Age: 30

The template is the first argument. The marker %s is replaced by the next text value, %d by the next whole number, and \n adds a line break at the end. Unlike echo, printf does not add a newline for you.

Understanding Exit Status

After each command, Bash stores a number from 0 to 255 in the special variable $?. By convention:

  • 0 means the command succeeded.
  • Any other number means something went wrong, and different numbers can describe different problems.

Check it right after a command:

true
echo "status=$?"

Output:

status=0

The true command does nothing and always succeeds. The command false does nothing and always fails:

false
echo "status=$?"

Output:

status=1

A real failure produces an error message as well. Asking ls to list a directory that does not exist gives:

ls /nonexistent_dir
echo "status=$?"

Output:

ls: cannot access '/nonexistent_dir': No such file or directory
status=2

The first line is the error message from ls. The second line shows that its exit status was 2. Notice that $? always describes the most recent command, so the value changes every time you run something new. Because echo is also a command, it sets $? to 0 as soon as it finishes. Read the value immediately after the command you care about, or copy it into a variable first.

When the Command Does Not Exist

If Bash cannot find the first word anywhere, it prints an error and sets the status to 127:

foo
echo "status=$?"

Output in an interactive shell:

bash: foo: command not found
status=127

This message appears most often because of a spelling mistake, because the program is not installed, or because the program's directory is not in your PATH. Commands are also case-sensitive, so LS is not the same as ls, and Bash reports LS: command not found.

Running More Than One Command on a Line

You can put several commands on one line when you separate them with a semicolon:

echo "First"; echo "Second"

Output:

First
Second

Bash runs the first command to completion and then runs the second. Semicolons and the other ways of joining commands have their own lesson later.

Putting the Commands Together

The following short session combines the commands from this lesson. Each line is typed at the prompt:

echo "Starting my first session"
whoami
date +%Y-%m-%d
echo $((6 * 7))
ls /nonexistent_dir
echo "last status: $?"

Sample output:

Starting my first session
student
2026-11-20
42
ls: cannot access '/nonexistent_dir': No such file or directory
last status: 2

Here is how it runs:

  1. echo prints the greeting.
  2. whoami prints your user name, which will differ from the sample.
  3. date +%Y-%m-%d prints today's date in year-month-day order.
  4. echo $((6 * 7)) evaluates the arithmetic and prints 42.
  5. ls /nonexistent_dir fails and prints an error message.
  6. The final echo reads $? and reports the failed ls status, 2, because ls was the last command to run before it.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Running Your First Bash Command and get answers drawn from it.

Signed-in readers only.