Skip to main content

Working with Files and Directories

1. Creating Files

Command Description Example
touch Creates an empty file or updates timestamp touch newfile.txt
echo Writes text to a file or stdout echo "Hello World" > hello.txt
cat > Creates a file with content from stdin cat > script.sh
> (redirect) Overwrites file content echo "content" > file.txt
>> (append) Appends content to a file echo "more" >> file.txt

Example: Creating a new file with content

echo "This is line one" > example.txt
echo "This is line two" >> example.txt

Example: Using touch to create an empty file

touch myscript.sh
Note: The touch command can also update timestamps of existing files.

2. Creating Directories

Command Description Examples
mkdir Creates new directories
mkdir mydir
mkdir -p parent/child/grandchild
mkdir -p Creates parent directories if they don't exist mkdir -p project/src/components
mkdir -m Set permissions for the new directory mkdir -m 755 secure_dir
Note: The -p flag is useful for creating nested directory structures without errors.

3. Copying Files and Directories

Command Description Examples
cp Copies files and directories cp file1.txt file2.txt
cp -r Recursively copies directories cp -r dir1/ dir2/
cp -p Preserves file attributes (timestamps, permissions) cp -p file1.txt file2.txt
cp -v Verbose mode, shows progress cp -v file1.txt file2.txt
cp -i Interactive mode, prompts before overwriting cp -i file1.txt file2.txt

Example: Copying a file with preserved attributes

cp -p /etc/passwd /backup/passwd.bak

Example: Recursively copying a directory

cp -r /home/user/documents/ /backup/documents/
Note: The -r flag is required when copying directories. Without it, cp will fail on directories.
Warning: Using cp without -i can overwrite files silently. Use -i or -n to prevent accidental overwrites.

4. Moving and Renaming

Command Description Example
mv Moves or renames files and directories mv file.txt /home/user/documents/<br>mv old_name.txt new_name.txt
Note: The mv command can also be used to rename files by moving them to the same directory with a new name.

5. Removing Files and Directories

Command Description Notes
rm Remove files or directories Use with caution; can't be undone
rm -r Remove directories recursively Deletes all contents inside directory
rm -f Force removal without prompts Suppresses error messages for non-existent files
rm -i Interactive removal Asks before deleting each file
rm -v Verbose output Lists each file as it's removed

Example: Remove a file

rm file.txt

Example: Remove a directory and its contents

rm -r directory/

Example: Force remove a file with no confirmation

rm -f file.txt
Note: The rm command permanently deletes files and directories. Use trash or similar tools if you want to recover deleted items.
Warning: Using rm -r / or similar destructive commands can cause system-wide damage. Always double-check paths.

Key Points

  • rm removes files and directories
  • Use -r to remove directories recursively
  • Use -f to force removal without prompts
  • Use -i for interactive confirmation
  • Use -v to see verbose output
Command Description Example
ln -s Create a symbolic link ln -s /path/to/target /path/to/link
ln -sf Force create symbolic link, overwrite if exists ln -sf /path/to/target /path/to/link
ln -sn Create symbolic link without following if target is a symlink ln -sn /path/to/target /path/to/link
ln -s /home/user/documents /home/user/docs
ln -s /etc/nginx.conf /etc/nginx/nginx.conf.backup
Note: Symbolic links are useful for creating aliases or maintaining references to files/directories without duplicating data.
Warning: If the target file or directory is moved or deleted, the symbolic link becomes broken.

Hard links are multiple directory entries that point to the same inode on a filesystem. They allow you to create additional names for the same file without duplicating the file's data.

Command Description Example
ln source_file link_name Creates a hard link named link_name pointing to source_file ln /home/user/document.txt /home/user/doc_backup.txt
Note: Hard links can only be created within the same filesystem. You cannot create a hard link across different mounted filesystems.
touch example.txt
ln example.txt backup.txt
ls -li example.txt backup.txt
  • Hard links share the same inode number, meaning they are indistinguishable from the original file.
  • Deleting one hard link does not affect others; the file remains accessible via remaining links.
  • Hard links cannot be created for directories on most Unix-like systems.
  • They do not preserve symbolic links or their targets.

8. Displaying File Contents

Command Description Usage Example
cat Concatenates and displays file contents cat filename.txt
less Opens file in a pager for scrolling less largefile.txt
more Displays file content one screen at a time more document.txt
head Displays first 10 lines of a file head -n 20 data.log
tail Displays last 10 lines of a file tail -f /var/log/syslog

Example: Using cat to view file contents

cat /etc/passwd

Example: Using head to view first lines of a file

head -n 5 /var/log/messages

Example: Using tail to follow log file changes

tail -f /var/log/nginx/access.log
Note: The less command is preferred over more for better navigation features.

9. Following File Updates

Command Description Usage
tail -f Displays the last 10 lines of a file and follows new content as it is added tail -f /var/log/syslog
tail -F Same as tail -f, but also handles file rotation tail -F /var/log/application.log
inotifywait Watches filesystem events for file changes (requires inotify-tools) inotifywait -m /path/to/file

Example: Watching Log File Changes

tail -F /var/log/nginx/access.log

Example: Using inotifywait for File Changes

inotifywait -m /home/user/documents/report.txt
Note: tail -F is preferred over tail -f when dealing with log files that may be rotated.

10. Counting Lines, Words, Characters

Command Description Example
wc Count lines, words, and characters in files wc file.txt
wc -l Count lines only wc -l file.txt
wc -w Count words only wc -w file.txt
wc -c Count characters only wc -c file.txt
wc -L Print the length of the longest line wc -L file.txt

Example: Using wc command

# Count lines, words, and characters in a file
wc file.txt

# Output:
# 10 25 150 file.txt

Example: Counting lines only

# Count only the lines in a file
wc -l file.txt

# Output:
# 10 file.txt

11. Comparing Files

Command Description Usage Example
diff Compares files line by line and shows differences diff file1.txt file2.txt
diff -u Shows unified diff format with context lines diff -u file1.txt file2.txt
diff -r Recursively compares directories diff -r dir1/ dir2/
cmp Compares files byte by byte, reports first difference cmp file1.txt file2.txt
diff -q Quiet mode, only reports whether files differ diff -q file1.txt file2.txt

Example: Using diff to compare files

diff file1.txt file2.txt
# Output:
3d2
< line 3 in file1.txt
5a6
> line 5 in file2.txt

Example: Using cmp to compare files byte by byte

cmp file1.txt file2.txt
# Output:
file1.txt file2.txt differ: byte 15, line 3
Note: The diff command is useful for identifying textual differences between files, while cmp is more suitable for binary file comparison or when you need to know the exact byte position of differences.

12. Finding File Differences

Command Description Usage Example
diff Compares two files line by line and shows differences diff file1.txt file2.txt
diff -u Shows differences in unified format (more readable) diff -u file1.txt file2.txt
diff -r Recursively compares directories diff -r dir1/ dir2/
diff -q Quiet mode, only reports whether files differ diff -q file1.txt file2.txt

Example: Comparing Files with Unified Output

diff -u oldconfig.conf newconfig.conf
--- oldconfig.conf	2025-04-01 10:00:00
+++ newconfig.conf	2025-04-01 11:00:00
@@ -1,5 +1,5 @@
 server_port = 8080
-server_name = localhost
+server_name = production.example.com
 timeout = 30s
 max_connections = 100
 log_level = info
Note: The diff command uses - for lines removed and + for added lines in unified format.

Key Points

  • diff is the standard Unix utility for comparing files
  • -u flag provides a human-readable unified diff format
  • -r enables recursive directory comparison
  • -q is useful for quick checks without detailed output

Was this article helpful?