The head utility is an essential GNU core utility in Linux used daily by system administrators and software developers to inspect the leading lines of text files, system logs, and command pipelines. However, running a command or executing automated bash shell scripts frequently fails with the error message: ‘head: cannot open for reading: No such file or directory’. In addition to stopping script execution, this error often prints output where parts of a filename or command flags are treated as missing file targets. Here is why this error occurs and how to fix it across bash, zsh, and shell scripts.
Why Does the ‘head: cannot open for reading’ Error Occur?
The GNU head command expects either one or more valid file paths as positional arguments or input passed via standard input (stdin). When it cannot locate the target, the breakdown typically involves:
- Unquoted Filenames Containing Spaces: When a file path containing spaces (e.g.,
system report.log) is passed without quotation marks, bash splits the argument into separate tokens, causingheadto look for a file namedsystemand another namedreport.log. - Unquoted Variable Expansions in Shell Scripts: Writing
head $FILEinside a shell loop when$FILEcontains spaces, tabs, or newlines results in word splitting. - Missing Hyphen in Standard Input Pipelines: Attempting to supply options or combining flags while redirecting standard input without adhering to POSIX command-line syntax.
- Wildcard Globbing Failures (Null Glob): Using glob patterns like
head *.loginside a directory where no files match the.logextension; by default, bash passes the unexpanded literal string*.logtohead. - Relative vs Absolute Path Misalignment: Running scripts via cron or from an unexpected working directory where relative paths like
head config/app.conffail to resolve.
Step 1: Properly Quote Filenames and Shell Variables
The most common cause of the error is unquoted variable expansion that splits filenames across spaces.
- Incorrect syntax that triggers the error:
Output:filename="server access log.txt" head -n 20 $filenamehead: cannot open 'server' for reading: No such file or directory head: cannot open 'access' for reading: No such file or directory head: cannot open 'log.txt' for reading: No such file or directory - Correct syntax wrapping the argument in double quotes:
filename="server access log.txt" head -n 20 "$filename" - Always wrap all variable expansions in double quotes throughout bash and shell scripts to prevent word splitting and pathname expansion.
Step 2: Correct Pipeline Syntax and Standard Input Handling
When piping the output of another command into head, you do not need to provide a file path argument.
- To read the top 10 lines of standard input from a stream:
cat /var/log/syslog | head -n 10 - Avoid providing extra trailing arguments or stray characters that
headmisinterprets as filenames:# Incorrect: dmesg | head -n 5 log.txt # Correct: dmesg | head -n 5 - If your script expects input from either a file or stdin dynamically, pass
-explicitly to signify standard input:cat input.txt | head -n 15 -
Step 3: Enable nullglob in Bash to Prevent Unmatched Wildcards
If you execute head *.txt in an empty directory, bash does not expand the wildcard. Instead, it passes *.txt literally, prompting head to look for a file with an asterisk in its name.
- In your shell script, enable the
nullglobshell option:shopt -s nullglob files=(*.txt) if [ ${#files[@]} -gt 0 ]; then head -n 5 "${files[@]}" else echo "No matching text files found." fi - With
nullglobactive, non-matching patterns expand to an empty list rather than passing the literal wildcard string tohead.
Step 4: Verify Current Working Directory and Relative Paths
Scripts executed via cron jobs or systemd services run with the root directory (/) or user home directory as the working directory, breaking relative paths.
- Always determine the directory of the executing script dynamically at the beginning of your bash script:
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" head -n 10 "$SCRIPT_DIR/logs/output.log" - Alternatively, verify file existence before invoking
head:TARGET_FILE="/var/log/nginx/access.log" if [ -f "$TARGET_FILE" ]; then head -n 25 "$TARGET_FILE" else echo "Error: Target file '$TARGET_FILE' does not exist." >&2 exit 1 fi
Adhering to double-quoted variable standards, validating file presence before execution, and using absolute directory referencing ensures your Linux command-line workflows and shell scripts operate reliably without encountering read errors.