3.3. Command Line Basics
Table of Contents
Why the Command Line Matters for Backend Developers
As a backend developer you will spend a lot of time in a terminal. You will:
- Start and stop servers
- Run tests
- Manage databases
- Inspect logs
- Work with Git
- Deploy applications
The command line gives you speed, scripting power, and remote access. You do not need to become a Linux guru now, but you must be comfortable with core commands and how to move around.
This chapter focuses on the basics that you will use almost every day.
Rule: For backend work, always know where you are in the filesystem, what files exist there, and what command you are running. A wrong command in the wrong directory can damage your project or system.
Throughout the examples, $ represents the shell prompt. You do not type the $ itself, only what comes after it.
Example:
$ pwd # You type: pwd (then press Enter)Opening a Terminal
How you open a terminal depends on your operating system.
- Linux
- Search for “Terminal” in your applications menu.
- Common names: Terminal, Konsole, GNOME Terminal, xterm.
- Shortcut on many systems:
Ctrl + Alt + T. - macOS
- Open Spotlight (
Cmd + Space), type “Terminal”, press Enter. - Or use iTerm2 if you install it later.
- Windows
For backend development, prefer one of: - Windows Terminal (from Microsoft Store)
- PowerShell
- WSL (Windows Subsystem for Linux) with a Linux distribution
In code examples, Linux, macOS, and WSL behave almost the same. PowerShell syntax sometimes differs, but you can usually adapt easily. If possible, use WSL so you get a Linux environment, which matches most backend servers.
The Prompt and Running Commands
A shell displays a prompt to show it is ready for a command. It often includes your user name, machine name, and current directory:
user@machine:~/projects/myapp$You then type a command, possibly with options and arguments:
$ command-name [options] [arguments]For example:
$ ls -l /etclsis the command-lis an option (also called a flag)/etcis an argument (what the command should act on)
Rule: Commands are case sensitive on Linux and macOS. LS is not the same as ls.
You can run built-in commands or programs installed on your system. Press Enter to execute.
Getting Help
You never need to memorize everything. Use built‑in help.
`--help` option
Many commands support:
$ command --helpExamples:
$ ls --help
$ mkdir --helpThis usually prints a short usage summary.
`man` pages
On Linux and macOS, you often have manual pages:
$ man lsUse:
Up/Downarrows orPageUp/PageDownto scrollqto quit
If man pages are missing in containers or minimal systems, rely on --help or online documentation.
`help` for shell built‑ins
Some commands are built into the shell, for example cd in bash:
$ help cdUnderstanding the Filesystem: Paths
A filesystem is organized like a tree. You navigate it with paths.
Absolute vs relative paths
- Absolute path: Starts from the filesystem root.
- On Linux/macOS:
/is the root directory. - Examples:
/home/user,/var/log,/usr/bin/python3 - Relative path: Starts from your current directory.
- Examples:
src,../logs,./main.py
Common special entries:
| Path | Meaning |
|---|---|
. | Current directory |
.. | Parent directory |
~ | Your home directory (Linux/macOS, WSL) |
Examples:
$ cd ~/projects # Go into "projects" in your home directory
$ cd .. # Go to parent directory
$ ls ./src # List contents of "src" inside current directoryWhere Am I? `pwd`
To know your current directory, use pwd (print working directory):
$ pwd
/home/user/projects/myapp
You will use pwd a lot while learning.
Example workflow:
$ pwd
/home/user
$ cd projects
$ pwd
/home/user/projectsListing Files: `ls`
To see what files and folders are in the current directory:
$ lsYou can also specify a path:
$ ls /etcUseful options:
| Command | Description |
|---|---|
ls | List names only |
ls -l | Long format with permissions and dates |
ls -a | Include hidden files (names start with .) |
ls -la or ls -al | Long format plus hidden files |
Example:
$ ls -la
drwxr-xr-x 8 user user 4096 Aug 25 10:00 .
drwxr-xr-x 10 user user 4096 Aug 25 09:00 ..
-rw-r--r-- 1 user user 220 Aug 25 10:00 .bash_logout
-rw-r--r-- 1 user user 3771 Aug 25 10:00 .bashrc
drwxr-xr-x 3 user user 4096 Aug 25 10:10 myappMoving Around: `cd`
cd changes your current directory.
Basic usage:
$ cd /absolute/path # Use an absolute path
$ cd relative/path # Use a relative path
$ cd # Go to your home directory
$ cd ~ # Also go to home
$ cd .. # Go up one directoryExample navigation:
$ pwd
/home/user
$ cd projects
$ pwd
/home/user/projects
$ cd myapp/src
$ pwd
/home/user/projects/myapp/src
$ cd ..
$ pwd
/home/user/projects/myappCreating Directories and Files: `mkdir` and `touch`
`mkdir` to create directories
$ mkdir myproject
$ ls
myproject
To create nested directories in one go, use -p:
$ mkdir -p myproject/app/templates
Without -p, mkdir fails if parent directories do not exist.
`touch` to create empty files
$ cd myproject
$ touch main.py
$ ls
main.py
If the file already exists, touch updates its last modified time but does not change its content.
Example project setup:
$ mkdir -p myapi/app
$ cd myapi/app
$ touch __init__.py main.py models.py
$ ls
__init__.py main.py models.pyViewing File Contents: `cat`, `less`, `head`, `tail`
Backend developers often inspect configuration files and logs from the terminal.
`cat` to print entire file
$ cat main.py
print("Hello, backend!")
For small files, cat is fine. For large files, it can flood your terminal.
`less` to scroll
less lets you scroll through long files:
$ less access.logControls:
Up/Downork/jto scrollqto quit/text+ Enter to search fortextnfor next match
`head` and `tail`
To see only the first or last lines:
$ head my.log # First 10 lines
$ tail my.log # Last 10 lines
$ head -n 20 my.log # First 20 lines
$ tail -n 50 my.log # Last 50 lines
tail -f is very useful for logs. It follows the file as it is written:
$ tail -f myapp.logThis shows new log entries as your backend runs.
Creating and Editing Files
You will need a text editor that runs in a terminal or in your GUI.
Simple file creation with redirection
You can quickly create small files using cat and redirection:
$ cat > hello.py
print("Hello from the command line")
# Press Ctrl + D to finish inputNow:
$ python hello.py
Hello from the command lineTerminal text editors
Common terminal editors:
nano(easiest for beginners)vimorvi(powerful, but steeper learning curve)emacs
Example with nano:
$ nano main.pyType your code, then:
Ctrl + Oto save, press Enter to confirm file nameCtrl + Xto exit
In many cases you will use a GUI editor or IDE (covered in another chapter), but knowing nano or vim is very helpful on remote servers.
Copying, Moving, and Renaming Files: `cp` and `mv`
Copying: `cp`
cp copies files or directories.
$ cp source.txt dest.txtCopy into a directory:
$ cp config.example.ini config.ini
$ cp main.py backup_main.py
To copy directories, use -r (recursive):
$ cp -r src src_backup
Be careful, cp can overwrite files without warning. Use -i (interactive) to be asked before overwriting:
$ cp -i config.ini /etc/myapp/config.iniMoving and renaming: `mv`
mv moves or renames files and directories.
Rename:
$ mv main_old.py main.pyMove a file into a directory:
$ mv main.py src/Move and rename in one command:
$ mv src/main.py app/server.py
You can also use -i for safety:
$ mv -i config.ini /etc/myapp/config.iniDeleting Files and Directories: `rm` and `rmdir`
Deleting is powerful and often final.
Rule: Check the path twice before running rm. A small mistake can delete important files. There is no “undo” in the shell.
Deleting files: `rm`
$ rm file.txtTo be asked before deleting each file, use:
$ rm -i file.txtDeleting directories
You can remove an empty directory with:
$ rmdir emptydirTo remove a directory and everything in it, use:
$ rm -r mydir
This is dangerous. Add -i to confirm each delete:
$ rm -ri mydirNever run commands like:
rm -rf /
rm -rf *unless you are absolutely sure what you are doing. They can erase huge parts of your filesystem.
For backend projects, a safe pattern is to only delete inside your project directory, not system paths.
Searching Files and Text: `find` and `grep`
You will often search for a file or a piece of configuration.
`find` to locate files and directories
Basic example, find all .py files under current directory:
$ find . -name "*.py"
./main.py
./app/models.py
./tests/test_main.pyExplanation:
.means start from current directory-name "*.py"matches Python files
Find directories named migrations:
$ find . -type d -name "migrations"`grep` to search inside files
Search for a word or phrase in files:
$ grep "DATABASE_URL" config.py
Search recursively in all .py files:
$ grep -R "DATABASE_URL" .
$ grep -R "DATABASE_URL" . --include="*.py"Useful options:
| Option | Meaning |
|---|---|
-i | Case insensitive search |
-n | Show line numbers |
-R | Search directories recursively |
Example:
$ grep -Rin "DEBUG" .
./settings.py:10:DEBUG = TrueRunning Programs: `python`, `pip`, `git`, etc.
The command line is how you run tools used in backend development.
Examples:
$ python main.py
$ python -m pytest # Run tests with pytest
$ pip install fastapi
$ git status
$ git commit -m "Add new endpoint"
$ uvicorn main:app --reload # Run a FastAPI app during developmentEach of these tools comes with its own options and subcommands. You will learn them gradually.
Use --help for each:
$ git --help
$ pip --help
$ uvicorn --helpPipes and Redirection: Combining Commands
The shell lets you connect commands so that the output of one becomes the input of another. This is very powerful.
Standard output and redirection
To send output to a file instead of the screen:
>overwrite file>>append to file
Examples:
$ ls > files.txt # Save ls output to files.txt, overwrite
$ ls >> files.txt # Append ls output to files.txt
$ cat config.py > backup_config.py
If you open files.txt, you will see the list of files.
Pipes `|`
The pipe symbol | passes the output of one command into another.
Example, see only Python files from ls:
$ ls | grep ".py"
main.py
models.pyTail the log file and show only lines containing "ERROR":
$ tail -f myapp.log | grep "ERROR"Pipes are essential for quickly inspecting logs and filtering information during debugging.
Environment Variables Basics
Environment variables are key-value pairs that affect how processes behave. They are often used for configuration and secrets, such as database URLs and API keys.
To print an environment variable:
$ echo $HOME
/home/user
$ echo $PATH
/usr/local/bin:/usr/bin:/bin:...To set an environment variable for a single command:
$ DEBUG=true python main.pyTo set one in the current shell session (bash style):
$ export DEBUG=true
$ echo $DEBUG
trueLater chapters have a dedicated discussion of environment variables, but you already see them often in backend examples, for example:
$ export DATABASE_URL="postgresql://user:pass@localhost:5432/mydb"
$ uvicorn main:app --reloadManaging Processes: `ps`, `kill`, and `Ctrl + C`
When you run a long command, such as a web server, it may keep running until you stop it.
Stopping a foreground process
Most of the time, you can stop the running command with:
Ctrl + C
Example:
$ uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000
# Press Ctrl + C to stopListing processes: `ps`
To see processes related to your shell:
$ ps
PID TTY TIME CMD
1234 pts/0 00:00:00 bash
1300 pts/0 00:00:00 python
1310 pts/0 00:00:00 ps
PID is the process ID.
To see more details:
$ ps aux | grep pythonKilling a process: `kill`
If a process is stuck and does not respond to Ctrl + C, you can use kill with its PID.
$ kill 1300 # Politely ask process 1300 to stop
$ kill -9 1300 # Forcefully kill process 1300 (use only if needed)Command History and Reuse
The shell keeps a history of commands you entered. This saves time.
Uparrow: Previous commandDownarrow: Next commandCtrl + R: Search in history
Example of Ctrl + R:
- Press
Ctrl + R - Type
uvicorn - You see:
(reverse-i-search)uvicorn': uvicorn main:app --reload` - Press Enter to run it again or use arrows to edit.
You can also list the history:
$ history
1 ls
2 cd projects
3 uvicorn main:app --reloadThen run a command by its number:
$ !3This runs the third command from history.
File Permissions Basics
On Linux/macOS, each file has permissions that control who can read, write, or execute it.
View permissions with ls -l:
$ ls -l main.py
-rw-r--r-- 1 user user 120 Aug 25 10:30 main.py
The first part -rw-r--r-- shows:
rreadwwritexexecute
They are grouped for:
- Owner
- Group
- Others
Basic patterns you will see:
| Pattern | Meaning |
|---|---|
-rw-r--r-- | Regular file, owner can edit |
-rwxr-xr-x | Executable file or script |
drwxr-xr-x | Directory |
To make a script executable:
$ chmod +x script.sh
$ ls -l script.sh
-rwxr-xr-x 1 user user ... script.shYou will use permissions more deeply when deploying to servers, but recognizing them now is helpful.
Practical Example: Creating a Simple Project via CLI
Let us combine several commands into a short, realistic workflow.
You want to start a new backend project called todo_api.
# 1. Go to home directory
$ cd ~
# 2. Create a projects directory if it does not exist
$ mkdir -p projects
$ cd projects
# 3. Create a project folder
$ mkdir todo_api
$ cd todo_api
# 4. Create basic structure
$ mkdir app
$ touch app/__init__.py app/main.py
# 5. List structure
$ ls
app
$ ls app
__init__.py main.py
# 6. Edit main.py with nano (or your editor)
$ nano app/main.py
Inside app/main.py, you might write:
def hello():
return "Hello, TODO API"
if __name__ == "__main__":
print(hello())Then run it:
$ python app/main.py
Hello, TODO APIYou have just created a simple project using only command line tools.
Good Habits for Using the Command Line
Some simple habits will save you pain.
Rule: Before running a destructive command like rm, mv, or cp, always:
- Run
pwdto verify where you are. - Run
lsto see what is there. - Double check the full path in your command.
Additional tips:
- Use tab completion. Type part of a file name and press
Tabto auto-complete or see suggestions. - Prefer short, clear commands. For example, use
cd ~/projects/myappinstead of manycd ... - Use history search (
Ctrl + R) instead of retyping long commands. - Keep a notes file with useful commands you use often.
- Do not run commands that you do not understand, especially if they include
rm -rf,sudo, or write to system directories like/etc,/usr, or/var.
Summary
In this chapter you learned:
- How to open and use a terminal
- How to navigate directories with
pwd,ls, andcd - How to create, inspect, copy, move, and delete files and directories with
mkdir,touch,cat,less,cp,mv,rm - How to search for files and text with
findandgrep - How to run programs and combine commands with pipes and redirection
- Basics of environment variables, processes, history, and permissions
These command line basics are enough to start doing real backend work, such as creating projects, running Python scripts, working with Git, and later managing services and servers. In the following chapters you will build on this foundation.
Views: 9
KAHIBARO