How to Fix ‘head: cannot open for reading: No such file or directory’ in Linux

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, causing head to look for a file named system and another named report.log.
  • Unquoted Variable Expansions in Shell Scripts: Writing head $FILE inside a shell loop when $FILE contains 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 *.log inside a directory where no files match the .log extension; by default, bash passes the unexpanded literal string *.log to head.
  • Relative vs Absolute Path Misalignment: Running scripts via cron or from an unexpected working directory where relative paths like head config/app.conf fail 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.

  1. Incorrect syntax that triggers the error:
    filename="server access log.txt"
    head -n 20 $filename
    Output:
    head: 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
  2. Correct syntax wrapping the argument in double quotes:
    filename="server access log.txt"
    head -n 20 "$filename"
  3. 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.

  1. To read the top 10 lines of standard input from a stream:
    cat /var/log/syslog | head -n 10
  2. Avoid providing extra trailing arguments or stray characters that head misinterprets as filenames:
    # Incorrect:
    dmesg | head -n 5 log.txt
    
    # Correct:
    dmesg | head -n 5
  3. 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.

  1. In your shell script, enable the nullglob shell option:
    shopt -s nullglob
    files=(*.txt)
    if [ ${#files[@]} -gt 0 ]; then
        head -n 5 "${files[@]}"
    else
        echo "No matching text files found."
    fi
  2. With nullglob active, non-matching patterns expand to an empty list rather than passing the literal wildcard string to head.

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.

  1. 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"
  2. 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.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.