File Operations in Bash
Now that you can navigate the file system, it's time to learn how to view, create, copy, move, and delete files โ the bread and butter of daily Bash usage.
Viewing File Contents
There are several commands to view file contents, each suited for different situations:
# cat โ display the entire file
cat myfile.txt
# less โ page through large files (q to quit)
less /var/log/syslog
# head โ show the first 10 lines (default)
head myfile.txt
head -n 5 myfile.txt # first 5 lines
# tail โ show the last 10 lines (default)
tail myfile.txt
tail -n 20 myfile.txt # last 20 lines
tail -f /var/log/syslog # follow (live updates)tail -f is incredibly useful for monitoring log files in real time. Press Ctrl + C to stop.
Copying, Moving & Deleting
# cp โ copy files and directories
cp source.txt destination.txt
cp -r src_dir/ dest_dir/ # copy directory recursively
# mv โ move or rename files
mv oldname.txt newname.txt # rename
mv file.txt /tmp/ # move to /tmp
# rm โ remove files
rm unwanted.txt
rm -i important.txt # ask before deleting
rm -r directory/ # delete directory and contents
rm -rf directory/ # force delete without promptsrm -rf is one of the most dangerous commands in Linux. It deletes everything without confirmation. Never run rm -rf / โ it would destroy your entire system.
File Permissions
Every file in Linux has three permission groups: Owner, Group, and Others. Each group can have Read (r), Write (w), and Execute (x) permissions.
# View permissions
ls -l myfile.txt
# -rw-r--r-- 1 user group 1234 Jun 21 12:00 myfile.txt
# Change permissions with chmod
chmod 755 script.sh # rwxr-xr-x
chmod +x script.sh # add execute permission
chmod u+w file.txt # add write for owner
# Change ownership
chown user:group file.txtThe numeric permission system uses three digits: Owner, Group, Others. Each digit is the sum of: Read=4, Write=2, Execute=1.
755= Owner: rwx (7), Group: r-x (5), Others: r-x (5)644= Owner: rw- (6), Group: r-- (4), Others: r-- (4)
Wildcards (Globbing)
Wildcards let you match multiple files with a pattern:
# * matches any number of characters
ls *.txt # all .txt files
cp *.jpg backup/ # copy all JPGs
# ? matches exactly one character
ls file?.txt # file1.txt, fileA.txt, etc.
# [] matches any one character inside brackets
ls file[123].txt # file1.txt, file2.txt, file3.txt
ls file[a-z].txt # filea.txt through filez.txtTry It Yourself
Summary
You've learned how to view files with cat, head, tail, and less; copy, move, and delete files; understand permissions; and use wildcards. These skills form the foundation for everything else in Bash.