Command Line Essentials
Navigate files, read output, pipe commands and use the shell productively.
What you will learn
- Navigate with cd and ls
- Create, copy and delete safely
- Use pipes and grep
The command line (terminal, shell) lets you control your computer by typing commands. Developers use it constantly because it is fast, scriptable and the same on servers as on laptops. Git, Docker, npm and most tools are driven from it. The examples use bash/zsh (macOS, Linux, WSL, Git Bash).
pwd # print working directory
ls # list files
ls -la # long format, including hidden files
cd projects # go into a folder
cd .. # go up one level
cd ~ # go home
cd - # go back to the previous folderPaths can be absolute (start with /, like /Users/amar/code) or relative to where you are. Press Tab to autocomplete names and the up arrow to recall previous commands.
mkdir notes # new folder
mkdir -p a/b/c # nested folders
touch todo.txt # empty file
cp todo.txt backup.txt # copy
mv backup.txt notes/ # move (also renames)
rm todo.txt # delete a file
rm -r notes # delete a folder and contentsrm is permanent. Double-check paths, and never run rm -rf on something you have not looked at. Try ls with the same path first.
cat file.txt # print whole file
less file.txt # scroll through (q to quit)
head -n 5 file.txt # first 5 lines
tail -n 20 app.log # last 20 lines
tail -f app.log # follow a growing log
wc -l file.txt # count linesgrep "error" app.log # lines containing "error"
grep -rn "TODO" src/ # search recursively, show line numbers
grep -i "warning" app.log # ignore case
find . -name "*.py" # find files by namePipes and redirection
The pipe | sends one command's output into another's input, letting you build powerful one-liners from small tools. > writes output to a file, and >> appends.
cat access.log | grep " 500 " | wc -l # how many 500 errors?
ls -l | sort -k5 -n | tail -3 # three biggest files
echo "hello" > out.txt
echo "world" >> out.txtecho $HOME
export API_URL="https://example.com" # set a variable for this session
chmod +x script.sh # make a file executable
./script.sh # run it
which python3 # where is this command?man ls # the manual page
ls --help # quick usage
history | grep gitTry it yourself
In a scratch folder, create a directory demo, write three lines into demo/list.txt with echo and >>, then use grep to print only the lines containing a chosen word.
Show solution
mkdir demo
echo "apple pie" >> demo/list.txt
echo "banana split" >> demo/list.txt
echo "apple tart" >> demo/list.txt
grep "apple" demo/list.txt