Reading configs and logs is most of what troubleshooting a server looks like.
Choose the viewer by file size and purpose:
cat fileprints a small file in one go,less filepages through anything, however large: Space and b to move,/textto search,nfor the next match,Gfor the end,qto quit,head -n 20andtail -n 20show the beginning or end,tail -f app.logfollows a file, printing new lines as they are written;tail -Fkeeps following across log rotation.
grep pattern files prints matching lines. Common flags: -i ignore case, -n line numbers, -r recursive through directories, -v invert (lines that do not match), -c count, -l only file names, -E extended regexes, -C 3 three lines of context. Combine them with pipes: grep -v '^#' sshd_config | grep -v '^$' shows a config without comments and blank lines.
wc -l counts lines, file identifies what a file actually contains (text, ELF binary, gzip...), and diff a b compares two files. Compressed logs can be read without unpacking using zcat, zless and zgrep.
Do not cat binary files or huge logs into the terminal; use less or head. Files you cannot read give "Permission denied", which often means you need sudo.
Example
cat /etc/hostname # print a small file
less /var/log/syslog # page: / search, n next, G end, q quit
head -n 3 /etc/passwd # first 3 lines
tail -n 20 /var/log/nginx/error.log
tail -F /var/log/nginx/access.log # follow new lines, survive rotation
wc -l /etc/passwd # 32 /etc/passwd
grep -n '^root' /etc/passwd # 1:root:x:0:0:root:/root:/bin/bash
grep -ri 'timeout' /etc/nginx/ # recursive, case-insensitive
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$' # config without comments
grep -c ' 500 ' access.log # count server errors
zgrep 'error' /var/log/syslog.2.gz
file /usr/bin/ls # ELF 64-bit LSB pie executable, x86-64 ...Remember
- less for big files, head/tail for ends, tail -f to follow
- grep -i -n -r -v -c cover most searches
- zcat, zless and zgrep read compressed logs
Watch out for
- Opening a multi-gigabyte log with cat or a text editor instead of less or tail.