File and directory commands
Commands to work and manage files and directories
In this tutorial, you’ll learn essential Linux commands used for managing files and directories.
Following are the list of essential commands that you must know while working in Linux OS.
1. pwd: Present working directory
This command is used to check the current working directory.
pwd
# Output
# /home/user
2. ls: List directory contents
Lists files and directories in the current location.
ls
# Example
# ls -l # shows detailed list (permissions, size, date)
# ls -a # show hidden files
3. cd: Navigating Directories
Used to navigate between directories.
cd ~/Documents # navigate to Documents directory
Go back to previous directory.
cd ..
Go to Home directory.
cd ~
Using Absolute vs Relative Path.
cd /home/user/Documents # Absolute
cd Projects # Relative
4. Creating Files & Directories
Create a directory.
mkdir demo_folder
Create Nested Directories.
mkdir -p project/src/components
NOTE: Before any other commands, let’s move inside demo_folder folder.
cd demo_folder
Create empty file.
touch empty.txt
Create file through Overwrite operator (>) and Append Operator (>>).
echo "Hello World." > file.txt
echo "Hello World New." >> file1.txt
echo "Bye Bye." >> file.txt # add "Bye Bye." after the "Hello World." in file.txt
Create file with content.
cat <<EOF > file2.txt
This is line1 of file2.txt
This is line2
This is line3
This is line4
EOF
5. Viewing File Content
Viewing File.
cat file.txt
# Output
# Hello World.
# Bye Bye.
cat file1.txt
# Output
# Hello World New.
cat file2.txt
# Output
# This is line1 of file2.txt
# This is line2
# This is line3
# This is line4
Scroll Large file.
less /var/log/auth.log
View first and last few lines from a file.
head /var/log/auth.log # show first 10 lines
head -5 /var/log/auth.log # show first 5 lines only
tail /var/log/auth.log # show last 10 lines
tail -5 /var/log/auth.log # show last 5 lines only
6. Copying Files & Directories
Copy File.
cp file.txt backup.txt
cat backup.txt
# Output
# Hello World.
# Bye Bye.
NOTE: Let’s change to the parent directory of demo_folder as our current directory is demo_folder.
cd ..
Now, let’s copy directory.
cp -r demo_folder backup_folder
ls
# Output
# backup_folder demo_folder
ls backup_folder
# Output will show same content as that in demo_folder
7. Moving & Renaming file and directory
Move file.
mv demo_folder/file.txt . # Move the file.txt inside demo_folder into current folder
ls
# Output
# backup_folder demo_folder file.txt
Rename file.
mv file.txt new_file.txt
ls
# Ouput
# backup_folder demo_folder new_file.txt
Rename folder.
mv demo_folder updated_folder
ls
# Output
# backup_folder new_file.txt updated_folder
8. Deleting files & directories
Delete file.
rm new_file.txt
ls
# Output
# backup_folder updated_folder
Delete directory.
rm -r backup_folder
ls
# Output
# updated_folder
You can delete the folder forcefully by adding -f flag as:
rm -rf folder-name