You’ve opened a terminal and typed commands like `ls`, `cd`, or `python script.py`—but maybe some didn’t execute as expected. To fix that, you need to understand *how* commands work, *where* they run, and *when* they fail. The core of terminal execution isn’t just typing; it’s knowing the hidden rules that turn your input into action. Below, you’ll get a step-by-step guide to running commands correctly, debugging errors, and optimizing workflows—whether you’re scripting, automating tasks, or troubleshooting system issues.
What You'll Need
- A terminal emulator (macOS/Linux: Terminal.app; Windows: Windows Terminal/PowerShell; WSL for native Linux).
- Basic familiarity with file paths (e.g., `/home/user/` or `C:\Users\`).
- Permissions to execute commands (root/admin may be needed for system-wide tools).
- A text editor (e.g., Vim, Nano, or VS Code) if writing scripts.
- Optional: A package manager (e.g., `apt`, `brew`, `choco`) for installing software via commands.
Step-by-Step Guide to Terminal Execution
- Open the Terminal.
- **macOS/Linux:** Press `Cmd + Space` to search for "Terminal," then open it.
- **Windows:** Launch either
Windows Terminalor open PowerShell (`Win + R` → type `powershell`). - **WSL (Windows Subsystem for Linux):** Launch your distro’s terminal from Start Menu. - Verify Your Shell.
Your terminal shows the current shell (e.g., Bash, Zsh, PowerShell). Run:
echo $SHELL(Bash/Zsh) or$env:PSVersionTable.PSVersion.Major(PowerShell) to confirm. If unsure, typeecho $0. Note: Some shells (like PowerShell) have quirks with pipes (`|`) or globbing (*). Adjust commands accordingly. - Run a Basic Command.
Test with
ls(list files) orpwd(print working directory). If you see errors like "Permission denied," try:ls -A(shows hidden files) orls -l(long listing, including permissions). Why it works: The shell executes the command in the current folder, respecting your permissions. - Navigate Filesystem.
Use:
cd /path/to/directory(e.g.,cd ~/Documents). Interactive mode: Typecdalone to list available folders. Note: Windows uses drive letters (e.g.,cd C:\Projects), whereas Linux/macOS uses forward slashes. - Execute a Script or Command File.
Save commands to a file (e.g.,
script.sh):#!/bin/bash echo "Hello, World!"Make it executable:chmod +x script.sh(Linux/macOS). Run it:./script.sh(orbash script.shif permissions are off). PowerShell:** Use.\script.ps1(or call it directly). - Use Built-in Commands.
Common commands for execution:
python script.py(run Python scripts).node app.js(run JavaScript).docker run image(start a container).ps aux(list all running processes).
- Run Commands with Arguments.
Example: Copy files with
cp file1.txt file2.txtor renamemv file.txt newname.txt. Quotes matter:**cp "folder/*" output/handles spaces in filenames. - Use Redirections.
Capture output:
command > output.txt(overwrites),command >> output.txt(appends). Pipe output to another command:ls | grep ".txt"(shows only .txt files). Note:** PowerShell usesOut-FileandSelect-Stringfor redirections. - Check Environment Variables.
Run:
echo $PATH(Bash) or$env:Path(PowerShell) to see where the shell looks for executables. Set a temporary variable:export MY_VAR=value(Bash/Zsh) or$env:MY_VAR="value"(PowerShell).
If That Did Not Work
If commands fail, check these steps in order:- Check for typos. Run
echo $?(Bash) or$LASTEXITCODE(PowerShell) to see the exit code (0 = success, non-zero = error). Example: `ls nonexistent.txt` → exit code 2 (No such file or directory). - Verify file permissions.
Use
ls -lto confirm the file has execute rights:drwxr-xr-x 2 root root 4096Fix withchmod +x filename(Linux/macOS). - Check shell syntax.
Test commands in an interactive shell (e.g.,
bash --login) before scripting. Example: Bash won’t execute a command without a newline at the end. - Restart the shell.
Open a new terminal or run
exec bash(Bash) to clear cached issues. - Reinstall the tool.
If packages (e.g., Python, Docker) are broken, reinstall via your package manager:
sudo apt update && sudo apt upgrade(Debian/Ubuntu).
Common Mistakes
- Forgetting shebang lines. Scripts like
#!/bin/bashmust be first in the file. Without it, the shell won’t recognize the interpreter. - Using incorrect paths. Windows uses backslashes (`\`), but Linux/macOS requires forward slashes (`/`). Use absolute paths (e.g., `/home/user/file`) for reliability.
- Ignoring exit codes. Commands like
rm file.txtmay silently fail if the file doesn’t exist. Always check output or useif ! rm file.txt; then echo "Error". - Running as root without need. Use
sudojudiciously—it can break system files. Prefer admin rights only for installation/deletion tasks. - Mixing shell types. Bash and Zsh handle redirections differently. Stick to one shell unless you’re scripting cross-shell.
Tips
- Use `history` to recall commands. Type
!10to rerun the 10th last command. Store frequently used commands in a~/.bashrcor~/.zshrcfile. - Enable command coloring. Add this to
~/.bashrc:alias ls='ls --color=auto'or usealias ls='colored-ls'(install via `brew install colored-ls`). - Use `man` for documentation. Run
man lsto see manual pages for commands. Example:man pythonfor Python syntax. - Test commands in a sandbox. Use Docker containers to isolate broken commands:
docker run -it ubuntu bash -c "command" - Enable verbose mode.
Add
-vto commands to see debug output:ls -vordocker -v run image.
Troubleshooting
- Command not found.
- Ensure the file is in your
PATH. Add it temporarily:export PATH=$PATH:/path/to/executable- For Python: Use the full path (e.g.,/usr/bin/python3 script.py). - Permission denied.
- For system files: Use
sudo(but avoid overusing it). - For user files: Addchmod +x file.shorchmod 755 file.sh. - Syntax errors in scripts.
- Use a linter like
shellcheck(install via `brew install shellcheck`). - Check for missing quotes or special characters. - Network issues (e.g., `curl` fails).
Test connectivity:
ping google.comIf blocked, try a VPN, disable firewalls, or use a different proxy. - Terminal hangs.
- Open a new terminal.
- Check for infinite loops in scripts (e.g.,
while true; do echo "..."; done).
Frequently Asked Questions
Why does python script.py fail but python3 script.py works?
Because Python versions may have different default paths. Run which python and which python3 to see which interpreter is being used.
How do I run a command in the background?
Use & or no newline. Example:while true; do sleep 1; echo "Running..."; done &
Check if it’s running with jobs (Bash) or Get-Process (PowerShell).
What’s the difference between cd and pwd?
cd changes the directory you’re in, while pwd prints the current path. They’re complementary.
How can I make a command persist across terminal sessions?
Add it to your shell config file:~/.bashrc (Bash) or ~/.zshrc (Zsh). Example:
alias myalias='command --args'
Then reload with source ~/.bashrc.
Why does ls | grep "error" not work?
On PowerShell, use Select-String -Pattern "error" instead. Bash/Zsh use pipes correctly.
How do I debug a slow terminal slowdown?
Check for resource hogs:top (Bash) or htop (install via brew install htop).
Kill processes if needed with kill -9 PID.