Running standard shell commands like ls *, rm *.log, or cp * /backup/ on a Linux directory containing tens of thousands of files only to be halted by the error bash: /bin/ls: Argument list too long (or cp: Argument list too long) prevents file management. In the Linux kernel, this error corresponds to system error code E2BIG. When you execute a command with wildcards (*), Bash expands every matching file name into a massive space-separated string before passing it to the execve() system call. If this argument string exceeds the kernel’s memory limit (ARG_MAX), the kernel rejects the execution.
Understand the Kernel ARG_MAX Memory Boundary
The Linux kernel limits the maximum memory buffer dedicated to command-line arguments and environment variables passed to new processes.
- To inspect the current argument memory ceiling on your system, execute:
getconf ARG_MAX - On modern Linux distributions,
ARG_MAXis typically between 2 MB and 4 MB (e.g.2097152bytes). - If a directory contains 100,000 files whose combined path characters exceed 2 MB, expanding a wildcard like
*instantly breachesARG_MAX. - The resolution is to avoid letting Bash expand wildcards in a single batch, streaming file names through pipes instead.
Use the find Command with -exec to Process Files Safely
The find utility bypasses Bash shell wildcard expansion entirely by querying directory inodes directly at the filesystem level.
- To list files without triggering argument overflow:
find . -maxdepth 1 -name "*.log" - To delete millions of files safely without using
rm *:find . -maxdepth 1 -name "*.log" -delete - To move or copy files using
-exec:find . -maxdepth 1 -name "*.csv" -exec mv {} /target/directory/ \; - The
{}placeholder represents each file, and\;executes the command individually per item without expanding an oversized argument string.
Process Large Batches Efficiently Using xargs
Executing commands individually with -exec ... \; can be slow. Combining find with xargs chunks arguments automatically up to the safe system limit.
- To batch-delete files safely:
find . -maxdepth 1 -name "*.tmp" -print0 | xargs -0 rm - The
-print0and-0flags delimit filenames using null characters (\0), ensuring filenames containing spaces or special characters process without error. - To move batches of files efficiently:
find . -maxdepth 1 -name "*.jpg" -print0 | xargs -0 -I {} mv {} /destination/folder/ xargsautomatically breaks the stream into discrete argument chunks that fit comfortably under theARG_MAXthreshold.
Iterate Over Files Using a Bash for Loop
If you prefer native shell scripting without external pipelines, use a for loop with filename streaming.
- Run the following shell loop directly in Terminal:
for f in *.txt; do [ -e "$f" ] || continue mv "$f" /backup/ done - Because Bash built-in loop structures handle iterations internally rather than packaging all arguments into a single
execvekernel call, loops rarely triggerE2BIGerrors.