Skip to main content

How to Check if File is Writable

• 2 min read
bash

Quick Answer: Check if File is Writable

To check if a file is writable in Bash, use the -w operator: if [ -w "$file" ]. This returns true if the file exists and your current user has write permission. Check directories the same way to verify write access.

Quick Comparison: File Write Permission Testing

TestPurposeSyntaxBest For
-wWrite permission[ -w "$file" ]Simple check
-f -wFile + writable[ -f "$f" -a -w "$f" ]Safety check
-d -wDirectory + writable[ -d "$d" -a -w "$d" ]Directory write
touch testTest writetouch "$f" 2>/dev/nullFallback check
stat %AFull permissionsstat -c %A "$file"Detailed view

Bottom line: Use -w for write permission check, combine with -f/-d for safety.


Testing Write Permission

Before writing to a file or directory, verify you have write permission. This prevents errors and lets you handle permission issues gracefully. The -w test operator checks if a file is writable.

Checking Write Permission

Use the -w operator:

#!/bin/bash

file="/tmp/test.txt"

if [ -w "$file" ]; then
  echo "File is writable"
else
  echo "File is not writable"
fi

Checking Before Writing

Always verify before attempting to write:

#!/bin/bash

file="/var/log/app.log"

if [ -w "$file" ]; then
  echo "New entry" >> "$file"
  echo "Entry logged successfully"
else
  echo "ERROR: Cannot write to log file"
  exit 1
fi

Checking Directory Write Permission

You need write permission on a directory to create files in it:

#!/bin/bash

dir="/home/user/downloads"

if [ -w "$dir" ]; then
  echo "Can create files in directory"
  touch "$dir/newfile.txt"
else
  echo "No write permission on directory"
fi

Combining Permission Checks

Check multiple permissions at once:

#!/bin/bash

file="/tmp/data.txt"

# Check if readable AND writable
if [ -r "$file" ] && [ -w "$file" ]; then
  echo "File is readable and writable"

  # Safe to read and modify
  content=$(cat "$file")
  echo "$content" | grep "pattern"
else
  echo "Insufficient permissions"
  exit 1
fi

Real-World Example: Safe File Update

#!/bin/bash

update_config() {
  local config_file="$1"
  local new_value="$2"

  # Verify file exists and is writable
  if [ ! -f "$config_file" ]; then
    echo "ERROR: Config file not found"
    return 1
  fi

  if [ ! -w "$config_file" ]; then
    echo "ERROR: No write permission on config file"
    return 1
  fi

  # Create backup before modifying
  cp "$config_file" "${config_file}.bak"

  # Update the file
  echo "$new_value" >> "$config_file"
  echo "Config updated successfully"
  return 0
}

update_config "/etc/myapp/config.conf" "new_setting=value"

Handling Read-Only Files

Check before attempting to delete or modify:

#!/bin/bash

secure_delete() {
  local file="$1"

  if [ ! -w "$file" ]; then
    echo "File is read-only, removing read-only flag..."
    chmod +w "$file"
  fi

  if [ -w "$file" ]; then
    rm "$file"
    echo "File deleted"
  else
    echo "ERROR: Cannot delete file"
    return 1
  fi
}

secure_delete "/tmp/oldfile.txt"

Practical Example: Logging System

#!/bin/bash

LOG_FILE="/var/log/myapp.log"

log_message() {
  local message="$1"
  local timestamp=$(date '+%Y-%m-%d %H:%M:%S')

  # Check if log file is writable
  if [ -w "$LOG_FILE" ]; then
    echo "[$timestamp] $message" >> "$LOG_FILE"
  else
    # Fallback to console if file not writable
    echo "[$timestamp] $message" >&2
  fi
}

log_message "Application started"
log_message "Processing request"
log_message "Application stopped"

Checking Permissions on Multiple Files

#!/bin/bash

check_writeable_files() {
  local dir="$1"
  local writable_count=0
  local readonly_count=0

  for file in "$dir"/*; do
    if [ -f "$file" ]; then
      if [ -w "$file" ]; then
        ((writable_count++))
      else
        ((readonly_count++))
      fi
    fi
  done

  echo "Writable files: $writable_count"
  echo "Read-only files: $readonly_count"
}

check_writeable_files "/tmp"

Permission Test Combinations

Test for common permission scenarios:

#!/bin/bash

file="/tmp/test.txt"

# File exists and is writable
if [ -f "$file" ] && [ -w "$file" ]; then
  echo "Can modify existing file"
fi

# File is writable but empty
if [ -w "$file" ] && [ ! -s "$file" ]; then
  echo "File is writable and empty"
fi

# Directory is writable (can create files)
if [ -d "$dir" ] && [ -w "$dir" ]; then
  echo "Can create files in directory"
fi

Important Notes

  • Write permission on a file means you can modify it
  • Write permission on a directory means you can create/delete files in it
  • The -w test checks your actual permissions, not just the file bits
  • Root user (UID 0) can usually write anywhere
  • Use [ ! -w "$file" ] to test if NOT writable

Quick Reference

# Check if file is writable
[ -w "$file" ] && echo "Writable"

# Check if NOT writable
[ ! -w "$file" ] && echo "Not writable"

# Combine with other tests
[ -f "$file" ] && [ -w "$file" ] && echo "Is writable file"

# Check directory
[ -d "$dir" ] && [ -w "$dir" ] && echo "Can create files"

Summary

Always test write permission before attempting to modify files. The -w operator is simple but essential for writing robust scripts that handle permission restrictions gracefully.