Bash error: "Read-only file system"

Fix "Read-only file system" errors in Bash. Usually a mount option, a filesystem error, or a container layer marked read-only. How to check and remount.

Error String

bash: cannot create file.txt: Read-only file system

Tldr

The filesystem backing the path is mounted read-only, either intentionally (mount -o ro, a Docker container with a read-only root, an immutable /nix or squashfs layer) or because the kernel detected corruption and remounted it read-only for safety. Check with `mount | grep <path>` and remount read-write, or write to a writable path instead.

Cause

Filesystems can be mounted read-only for several reasons: a deliberate security choice (containers run with --read-only, live CDs, /boot on some distros), an actual disk error where the kernel automatically remounts ext4/xfs read-only to prevent further corruption (visible in `dmesg`), or a network filesystem exported read-only by the server. Writing anywhere under such a mount point fails with this error regardless of file permissions.

Repro

$ mount | grep /data
/dev/sdb1 on /data type ext4 (ro,relatime)

$ echo hi > /data/file.txt
bash: /data/file.txt: Read-only file system

Fix

#!/usr/bin/env bash
set -euo pipefail

# Confirm the mount is read-only
mount | grep " /data "

# Check dmesg for filesystem errors that forced a read-only remount
dmesg | tail -n 30 | grep -i "read-only\|ext4"

# If it's just a mount option, remount read-write
sudo mount -o remount,rw /data

# If dmesg shows corruption, unmount and fsck instead
sudo umount /data
sudo fsck /dev/sdb1

# In Docker, drop --read-only or add a writable volume/tmpfs
docker run --read-only --tmpfs /tmp myimage

Explanation

Never blindly remount read-write if dmesg shows disk errors — run fsck first or you risk further corruption. In containers, the fix is usually architectural: mount a writable volume or tmpfs at the specific path that needs writes instead of removing --read-only entirely.

Faq

Q

Why does chmod not fix this?

A

chmod changes file permissions, but "Read-only file system" happens at the mount level, above individual file permissions. No permission change can make a read-only mount writable.

Q

How do I know if it is a hardware problem?

A

Run `dmesg | grep -i error` right after the failure. If the kernel logs mention I/O errors or "Remounting filesystem read-only", treat it as a disk health issue and back up data before running fsck.

Q

Why does this happen in Docker even though I have root?

A

Containers started with --read-only make the entire root filesystem read-only regardless of the user. Mount a volume, bind mount, or tmpfs at the specific directory your process needs to write to.