Bash Tutorial menu

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.

PathMeaning
/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.txtAn absolute path, starting from /
docs/notes.txtA relative path, starting from where you are

Where Am I? pwd and ls

Example

bash
pwd
ls
ls -l
ls -a
  • pwd prints the current folder.
  • ls lists files and folders.
  • ls -l shows a long list with sizes, dates and permissions.
  • ls -a also 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 -
CommandGoes to
cd folderA folder inside the current one
cd ..The parent folder
cd ~ or just cdYour 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
ls
Output
Buy notebook
notes  todo.txt
  • mkdir makes a folder. -p creates parent folders too, and does not complain if they exist.
  • touch creates an empty file (or updates the time of an existing one).
  • cat prints 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
ls
Output
notes  notes-copy  tasks.txt
CommandWhat it does
cp a bCopies file a to b
cp -r a bCopies a folder and everything inside it
mv a folder/Moves a into a folder
mv old newRenames a file or folder

Deleting

Example

bash
rm tasks.txt
rm -r notes-copy
rmdir empty-folder
  • rm deletes files.
  • rm -r deletes a folder and everything inside it.
  • rmdir deletes 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

CommandUse
cat fileShow the whole file
less fileScroll through a long file (press q to quit)
head -n 5 fileShow the first 5 lines
tail -n 5 fileShow the last 5 lines
wc -l fileCount 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?

Learn Bash with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp