How to Fix Linux bash: No such file or Directory Error
In this tutorial, you'll learn about How to Fix Linux bash: No such file or Directory Error. We cover key concepts, practical examples, and best practices.
You try to run a script and get No such file or directory even though the file exists — the interpreter specified in the shebang is missing, or the file has Windows line endings.
The Problem
bash: ./script.sh: No such file or directory
But the file exists:
ls -la script.sh
-rwxr-xr-x 1 user user 1024 Jun 24 10:00 script.sh
Step-by-Step Fix
Step 1: Check the shebang line
head -1 script.sh
If missing or pointing to a non-existent interpreter:
#!/usr/bin/python3 # WRONG if python3 not installed
Fix by using the correct interpreter path:
#!/usr/bin/env python3
Step 2: Verify the interpreter exists
which bash
Or check the shebang path:
ls -la /bin/bash
Step 3: Check for Windows line endings
file script.sh
If it shows CRLF or with CRLF line terminators:
# WRONG — CRLF line endings
script.sh: ASCII text, with CRLF line terminators
# RIGHT — Unix line endings
sed -i 's/\r$//' script.sh
Or use dos2unix:
sudo apt install dos2unix
dos2unix script.sh
Step 4: Check if the file is a symlink pointing nowhere
ls -la script.sh
If it shows:
lrwxrwxrwx 1 user user 24 Jun 24 10:00 script.sh -> /nonexistent/path
The target is missing. Recreate the symlink or install the target.
Step 5: Check for spaces or special characters in the filename
ls -b script.sh
If the filename has hidden characters, rename it:
mv script.sh newscript.sh
Step 6: Check for missing shared libraries
ldd script.sh
For binaries, this shows missing libraries.
Prevention Tips
- Use
#!/usr/bin/env bashinstead of hardcoded paths - Set Git to auto-convert line endings:
git config --global core.autocrlf input - Test scripts directly with the interpreter:
bash script.sh - Use
shellcheckto lint shell scripts - Avoid spaces in filenames
Common Mistakes with file not found
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world LINUX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro