Bash errors

stderr

Errors are printed to the terminal differently from ordinary messages.

Ordinary messages are stdout, file descriptor number 1

Errors are stderr, file descriptor number 2

Let us look at an example of an error message.

To do this, let us list a directory that does not exist

ls /etcw

ls: cannot access '/etcw': No such file or directory

Trying to redirect the error to a file with > will not help

ls /etcw > err

zsh: file exists: err

The reason is that > is the equivalent of 1> while we need 2>

ls /etcw 1> err
cat err

ls: cannot access '/etcw': No such file or directory

Error messages often come mixed with ordinary ones.

For example, you need to search in a directory where some subdirectories are inaccessible because of insufficient permissions.

find /etc -type l

/etc/mtab find: ‘/etc/grub.d’: Permission denied /etc/pki/ca-trust/source/ca-bundle.legacy.crt /etc/pki/java/cacerts /etc/pki/tls/cert.pem /etc/pki/tls/certs/ca-bundle.crt /etc/pki/tls/certs/ca-bundle.trust.crt find: ‘/etc/pki/CA/private’: Permission denied find: ‘/etc/pki/Pegasus’: Permission denied find: ‘/etc/pki/rsyslog’: Permission denied …

To avoid being distracted by the errors, you can redirect them to /dev/null

find /etc -type l 2> /dev/null

/etc/mtab /etc/pki/ca-trust/source/ca-bundle.legacy.crt /etc/pki/java/cacerts /etc/pki/tls/cert.pem /etc/pki/tls/certs/ca-bundle.crt /etc/pki/tls/certs/ca-bundle.trust.crt /etc/systemd/system/multi-user.target.wants/remote-fs.target /etc/systemd/system/multi-user.target.wants/crond.service /etc/systemd/system/multi-user.target.wants/rhel-configure.service /etc/systemd/system/multi-user.target.wants/libstoragemgmt.service …

If you need to redirect both the errors and the standard output, run:

find /etc -type l &> everything.log

1: !#/bin/bash: not found

Error

1: !#/bin/bash: not found

Occurs if you swap ! and # in the first line of the script

The correct way is

#!/bin/bash

VAR: command not found

Error

VAR: command not found

Occurs if you mistakenly put a space at the equals sign when assigning a value to a variable

The correct way is

VAR='https://eth1.ru'

The wrong way is

VAR = 'https://eth1.ru'

There must be no spaces around =.

ls: command not found

If you get the error

ls: command not found
rm: command not found

Or some other basic command - most likely something is wrong with the system variable PATH perhaps at some point you changed PATH manually, or you do it in your script

PATH="/var/lib"

If the error is in a script, find where you use the PATH variable and, if you do it deliberately, fix the error. If you chose such a variable name by accident, change it to another one.

Article author: Andrei Olegovich