</>
Skip to content
Bash lessons (22/29)

Bash — Files

File types

#!/bin/bash

file="test.txt"

[ -f "$file" ] && echo "Regular file"
[ -d "$file" ] && echo "Directory"
[ -L "$file" ] && echo "Symbolic link"
[ -r "$file" ] && echo "Readable"
[ -w "$file" ] && echo "Writable"
[ -x "$file" ] && echo "Executable"
[ -s "$file" ] && echo "Non-empty"

Creating files

#!/bin/bash

# Touch (create or update timestamp)
touch file.txt

# Echo to file
echo "Hello" > file.txt

# Cat with heredoc
cat > file.txt << EOF
Line 1
Line 2
Line 3
EOF

Reading files

#!/bin/bash

# Entire file
content=$(cat file.txt)

# Line by line
while IFS= read -r line; do
    echo "$line"
done < file.txt

# With line numbers
nl file.txt

Permissions

#!/bin/bash

chmod +x script.sh     # Make executable
chmod 755 script.sh    # rwxr-xr-x
chmod 644 file.txt     # rw-r--r--
chown user:group file  # Change owner

Symbolic links

#!/bin/bash

ln -s /path/to/original link_name  # Create symlink
ls -l link_name                     # View symlink

Mini Practice

Write Bash code that:

  1. Checks file type and permissions
  2. Creates and reads a file
  3. Changes file permissions
  4. Creates a symbolic link

Up Next

In the next lesson, you'll learn about Directories — directory operations.

Related Topics

Frequently Asked Questions about Files

What is Files in Bash?

Files is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Files?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Files.

Why is Files important in Bash?

Files is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.