Bash Files and Folders
Most Bash work is moving around folders and working with files. These commands are the ones you will type every day.
Paths
A path tells Bash where a file or folder is.
| Path | Meaning |
|---|---|
/ | The root, the top of the whole file system |
~ | Your home folder, for example /home/ali |
. | The current folder |
.. | The parent folder (one level up) |
/home/ali/notes.txt | An absolute path, starting from / |
docs/notes.txt | A relative path, starting from where you are |
Where Am I? pwd and ls
Example
bash
pwd
ls
ls -l
ls -apwdprints the current folder.lslists files and folders.ls -lshows a long list with sizes, dates and permissions.ls -aalso shows hidden files, whose names start with a dot.
Options like -l and -a can be joined: ls -la.
Moving Around with cd
Example
bash
cd /tmp
pwd
cd ~
cd ..
cd -| Command | Goes to |
|---|---|
cd folder | A folder inside the current one |
cd .. | The parent folder |
cd ~ or just cd | Your home folder |
cd - | The folder you were in before |
Creating Files and Folders
Example
bash
mkdir project
cd project
mkdir -p notes/week1
touch todo.txt
echo "Buy notebook" > todo.txt
cat todo.txt
lsOutput
Buy notebook notes todo.txt
mkdirmakes a folder.-pcreates parent folders too, and does not complain if they exist.touchcreates an empty file (or updates the time of an existing one).catprints a file's contents.
Copying, Moving and Renaming
Example
bash
cp todo.txt backup.txt
mv backup.txt notes/
mv todo.txt tasks.txt
cp -r notes notes-copy
lsOutput
notes notes-copy tasks.txt
| Command | What it does |
|---|---|
cp a b | Copies file a to b |
cp -r a b | Copies a folder and everything inside it |
mv a folder/ | Moves a into a folder |
mv old new | Renames a file or folder |
Deleting
Example
bash
rm tasks.txt
rm -r notes-copy
rmdir empty-folderrmdeletes files.rm -rdeletes a folder and everything inside it.rmdirdeletes only empty folders.
Be careful: the terminal has no Recycle Bin. A file deleted with rm is gone. Use rm -i to make Bash ask before each deletion, and never run rm -rf unless you are completely sure of the path.
Viewing Files
| Command | Use |
|---|---|
cat file | Show the whole file |
less file | Scroll through a long file (press q to quit) |
head -n 5 file | Show the first 5 lines |
tail -n 5 file | Show the last 5 lines |
wc -l file | Count the lines |
Wildcards
The * wildcard matches any text in file names:
Example
bash
ls *.txt
cp *.jpg photos/
rm report-*.pdf*.txt means "every file ending in .txt". ? matches exactly one character.
Exercise
Exercise
Which command takes you one folder up?
