Command Line Basics: Bash Commands for Beginners
Why Programmers Use the Terminal
Clicking through folders works for everyday computing, but programmers spend much of their time typing commands into a terminal (also called the command line or shell). It looks old-fashioned, but it is faster for many jobs, it can be automated, and it is the only way to work on most servers and cloud machines. Running Python scripts, installing packages with pip or npm, using Git and deploying a website all happen in the terminal.
This tutorial covers command line basics for beginners, using the Bash shell found on Linux and macOS (and on Windows through Git Bash or WSL): navigating folders, creating, copying, moving and deleting files, viewing file contents, searching with grep and find, redirection and pipes, combining small tools to analyse data, environment variables and PATH, permissions, and writing a first shell script. The equivalent Windows PowerShell commands are listed at the end.
Opening the Command Line and Reading the Prompt
- Linux: press Ctrl + Alt + T, or search for "Terminal".
- macOS: open Terminal from Applications, then Utilities.
- Windows: install Git for Windows and open Git Bash (or install WSL for a full Linux system). PowerShell also works, but some commands differ.
The terminal shows a prompt, often ending in $, and waits for a command. In the examples below, lines beginning with $ are commands you type (without the $), and the other lines are what the terminal prints back. Every command has the form command -options arguments. For example, in ls -F data, ls is the command, -F is an option and data is the argument.
Navigating the File System
Files are arranged in a tree of folders, called directories. At any moment, the terminal is "in" one of them, the current working directory.
pwd(print working directory) shows where you are.lslists the contents of a directory.ls -Fmarks folders with a trailing/,ls -lshows details such as sizes and dates, andls -aincludes hidden files, whose names start with a dot.cd folder(change directory) moves into a folder.cd ..goes up one level,cd ~(or justcd) goes to your home directory, andcd -returns to the previous directory.
Paths
- An absolute path starts from the root of the file system, such as
/home/ada/project/notes. On Git Bash, the C: drive appears as/c/. - A relative path starts from the current directory, such as
project/notes. A single dot.means "this directory", and..means "the parent directory". ~is a shortcut for your home directory.
Press Tab to auto-complete file and folder names, and the up arrow to recall earlier commands. These two keys save an enormous amount of typing.
Creating Files and Folders
In a terminal:
$ mkdir project $ cd project $ mkdir notes data $ touch notes/todo.txt $ ls -F data/ notes/
mkdirmakes one or more directories.mkdir -p a/b/ccreates the whole chain at once.touchcreates an empty file (or updates the modification time of an existing one).
Avoid spaces in file and folder names. If you must use them, put the name in quotes: cd "My Documents".
Writing to Files and Viewing Them
echo prints text. The > symbol redirects that output into a file, replacing its contents, and >> appends to the end of it.
In a terminal:
$ echo "Read chapter 3" > notes/todo.txt $ echo "Solve past questions" >> notes/todo.txt $ cat notes/todo.txt Read chapter 3 Solve past questions
Ways to look inside files:
cat fileprints the whole file.less fileopens a scrollable viewer. Use the arrow keys or the space bar to move,/wordto search andqto quit.head -n 5 fileshows the first 5 lines, andtail -n 5 filethe last 5.tail -f logfilekeeps showing new lines as they are added, which is handy for watching a server's log.wc -l filecounts the lines (andwc -wthe words).
To edit files in the terminal, beginners usually find nano file the easiest editor. Its shortcuts are listed at the bottom of the screen: Ctrl + O saves and Ctrl + X exits. Many programmers also open a folder in VS Code from the terminal with code .
Copying, Moving and Deleting
In a terminal:
$ cp notes/todo.txt notes/backup.txt $ mv notes/backup.txt data/ $ ls notes data data: backup.txt notes: todo.txt $ rm data/backup.txt
cp source destinationcopies a file. Usecp -rto copy a whole folder.mv source destinationmoves a file. It also renames one:mv old.txt new.txt.rm filedeletes a file, andrm -r folderdeletes a folder and everything in it.
Warning: rm does not use a recycle bin, so deleted files are gone. Double-check before you press Enter, especially with -r and wildcards. Use rm -i to be asked for confirmation for each file.
Wildcards
The shell expands patterns before running the command: * matches any characters and ? matches exactly one. So ls *.csv lists every CSV file, and cp data/*.txt backup/ copies all the text files in data.
Searching: grep and find
To practise, create a small CSV file of results. printf works like echo, but it understands \n as a new line.
In a terminal:
$ printf "name,dept,score\nAda,Physics,72\nBayo,Physics,58\nChidi,Maths,90\nDami,Maths,45\nEfe,Physics,81\n" > data/results.csv $ wc -l data/results.csv 6 data/results.csv $ head -n 3 data/results.csv name,dept,score Ada,Physics,72 Bayo,Physics,58
grep prints the lines that contain a pattern:
In a terminal:
$ grep Physics data/results.csv Ada,Physics,72 Bayo,Physics,58 Efe,Physics,81 $ grep -c Physics data/results.csv 3 $ grep -n Maths data/results.csv 4:Chidi,Maths,90 5:Dami,Maths,45
Useful options are -i (ignore case), -n (show line numbers), -c (count matching lines), -v (show lines that do not match) and -r (search every file in a folder, recursively). For example, grep -rn "TODO" . finds every TODO comment in a project.
find searches for files by name, type, size or date:
In a terminal:
$ find . -name "*.txt" ./notes/todo.txt
Pipes: Combining Small Tools
The pipe symbol | sends the output of one command straight into the next. Each Unix tool does one small job well, and pipes join them into powerful one-line programs.
In a terminal:
$ grep -i maths data/results.csv | cut -d, -f1
Chidi
Dami
$ tail -n +2 data/results.csv | sort -t, -k3 -nr | head -n 3
Chidi,Maths,90
Efe,Physics,81
Ada,Physics,72
$ cut -d, -f2 data/results.csv | tail -n +2 | sort | uniq -c
2 Maths
3 Physics
Reading the pipelines from left to right:
cut -d, -f1splits each line at the commas and keeps field 1, the name.tail -n +2prints from line 2 onwards, skipping the header row.sort -t, -k3 -nrsorts by the third comma-separated field, numerically (-n) and in reverse (-r), giving the top three scores.sort | uniq -ccounts how many times each value occurs.uniqonly merges neighbouring duplicates, which is why the list is sorted first.
More Redirection
command > filesaves the normal output (standard output) to a file.command 2> filesaves error messages (standard error) to a file.command > out.txt 2>&1sends both into the same file.command < filefeeds a file into a command as its input.
In a terminal:
$ ls nofile 2> errors.txt $ cat errors.txt ls: cannot access 'nofile': No such file or directory
Variables, Environment Variables and PATH
The shell can store values in variables. There must be no spaces around the =, and a $ reads the value back.
In a terminal:
$ GREETING="Good morning" $ echo "$GREETING, class" Good morning, class $ echo $((7 * 6)) 42
Environment variables are variables that programs started from the shell can also read. export NAME=value creates one, and env lists them all. They are commonly used for settings and secrets, such as DATABASE_URL or an API key, so that they never have to be written into the code.
One special environment variable is PATH: a list of folders, separated by colons, where the shell looks for commands. When you type python, the shell searches each folder in PATH in turn. "Command not found" usually means the program is not installed or its folder is not in PATH. which python shows which file will actually run.
Permissions and Your First Shell Script
A shell script is a text file of commands that run one after another. Save this as greet.sh:
In a terminal:
#!/bin/bash
# greet.sh: say hello to everyone named on the command line
for name in "$@"; do
echo "Hello, $name!"
done
echo "Greeted $# people."
- The first line, the shebang, says which program should run the script.
"$@"stands for all the arguments given to the script, and$#is how many there are.$1is the first argument,$2the second, and so on.
On Linux and macOS, every file has permissions that control who can read (r), write (w) and execute (x) it. ls -l shows them, as in -rwxr-xr-x. A new script must be made executable with chmod +x before it can run:
In a terminal:
$ chmod +x greet.sh $ ./greet.sh Ada Bayo Chidi Hello, Ada! Hello, Bayo! Hello, Chidi! Greeted 3 people.
The ./ tells the shell to run the file from the current directory, which is not normally in PATH. Scripts like this automate repetitive jobs such as backups, renaming batches of files and running tests.
Getting Help and Staying Safe
man commandopens the manual for a command (pressqto quit), andcommand --helpprints a shorter summary.historylists your previous commands. Ctrl + R searches them as you type.- Ctrl + C stops the command that is currently running. Ctrl + L (or
clear) clears the screen. sudoruns a command as the administrator. Use it only when you understand exactly what the command does, and never paste commands from the internet that you do not understand.
Bash and PowerShell Equivalents
If you use Windows PowerShell instead of Bash, many common commands have aliases that work the same way (ls, cd, pwd, cat, cp, mv, rm and mkdir). The main differences are:
touch filebecomesNew-Item filegrep pattern filebecomesSelect-String pattern filehead -n 5 filebecomesGet-Content file -TotalCount 5rm -r folderbecomesRemove-Item folder -Recurseexport NAME=valuebecomes$env:NAME = "value"which pythonbecomesGet-Command python
Common Mistakes on the Command Line
- Using
>when you meant>>. A single>wipes the existing contents of the file. - Running
rm -rwith a wildcard in the wrong folder. Check where you are withpwdfirst. - Putting spaces around
=in a variable assignment.NAME = Adatries to run a command called NAME. - Forgetting quotes around names with spaces, so that the shell treats them as two separate arguments.
- Running a script without
./or without first making it executable.
Command Line: Practice Exercises
- Create a folder
practicecontaining two subfolders,srcanddocs, with one command. - Write three lines into
docs/plan.txtusingechowith>and>>, then display the file. - Using the results file from this tutorial, print only the names of the Physics students.
- Print the lowest score in the results file.
- Write a script
count.shthat prints how many lines each file given on the command line has.
Sample solutions:
In a terminal:
$ mkdir -p practice/src practice/docs $ echo "Week 1: basics" > practice/docs/plan.txt $ echo "Week 2: pipes" >> practice/docs/plan.txt $ echo "Week 3: scripts" >> practice/docs/plan.txt $ cat practice/docs/plan.txt Week 1: basics Week 2: pipes Week 3: scripts $ grep Physics data/results.csv | cut -d, -f1 Ada Bayo Efe $ tail -n +2 data/results.csv | cut -d, -f3 | sort -n | head -n 1 45
In a terminal:
#!/bin/bash
# count.sh: print the number of lines in each file given as an argument
for file in "$@"; do
echo "$file: $(wc -l < "$file") lines"
done
Running ./count.sh data/results.csv practice/docs/plan.txt prints data/results.csv: 6 lines and practice/docs/plan.txt: 3 lines. The $( ) syntax runs a command and inserts its output, and wc -l < file prints only the number, without the file name.
Conclusion
The command line lets you work faster, automate tasks and use servers and developer tools. Navigate with pwd, ls and cd, using absolute and relative paths. Manage files with mkdir, touch, cp, mv and (carefully) rm. Read files with cat, less, head, tail and wc, and search with grep and find. Redirection (>, >>, 2>) saves output, and pipes (|) chain small tools like cut, sort and uniq into data-processing one-liners. Environment variables and PATH control how programs are found and configured, and executable shell scripts turn any sequence of commands into a reusable tool.