Table of Contents

Linux

Linux Commands Cheat Sheet





Help

COMMAND -h |less
COMMAND --help |less
man COMMAND
LANG=C  man COMMAND




System Commands

System Commands

shutdown bring the system down shutdown -h now ← -h = Halt or poweroff after shutdown
shutdown -r now ← -r : Reboot after shutdown
shutdown -r -F now ← -F : Force fsck after reboot.
halt stop the system. halt
reboot reboot the system. reboot
init init 1 #change to single usermode
uptime Tell how long the system has been running. uptime
runlevel find the previous and current system runlevel. runlevel
printenv print all or part of environment printenv
env run a program in a modified environment env
hostname show or set the system's host name hostname ← show the system's host name
I recommend uname -n for check hostanme.
hostname NEWHOSTNASME ← set the system's host name
uname print system information uname -a ← print all information (=uname --all)
uname -n ← show the system's host name (=uname --nodename)
locale Get locale-specific information. locale
locale -a |grep -i ja <- -a : --all-locales

Process Management

ps report a snapshot of the current processes. ps aux |grep httpd ← Check httpd rocess
ps aux | grep XXX | awk '{print $2}' | xargs kill -9
ps auxwf
ps auxwf |grep XXX
pgrep look up processes based on name and other attributes pgrep -f 'bash'
pgrep -lf 'bash' ← output with process name
pgrep -f 'bash' | xargs kill
pstree display a tree of processes pstree -a
pidof find the process ID of a running program pidof httpd
/bin/kill $(/sbin/pidof qmail-popup)
kill send a signal to a process kill -9 PID ← (-9 or -KILL = force-quit)
pkill signal processes based on name and other attributes pkill -f 'bash'
pkill -u user1
pkill java
pkill -f jar
killall kill processes by name killall vi
killall -i vi ← -i = Interactively
killall -HUP kterm
killproc
lsof list open files lsof -i
lsof -i -P ← no port names
lsof -i :80,443 ← Which process is using Port 80,443
Ctrl + C Stop running process
Ctrl + Z Suspend running process Move Running Process to Background
1. ctrl + z
2. jobs
3. bg
4. disown %JOBID
jobs The first form lists the active jobs. jobs -l ← List job
fg Resume jobspec in the foreground
bg Resume each suspended job jobspec in the background
nohup run a command immune to hangups, with output to a non-tty nohup command.sh &
disown disown %jobid
nice run a program with modified scheduling priority nice -n 19 test.sh
nice -n 19 ionice -c 3 CMD
nice -n 19 ionice -c 2 -n 7 COMMAND
renice alter priority of running processes renice 19 -p PID
you can check the nice whith “top” or “ps alx”.
ionice sets or gets process io scheduling class and priority ionice -p PID ← check
ionice -c 3 -p PID
nice -n 19 ionice -c 2 -n 7 COMMAND

Schedule

crontab maintain crontab files crontab -l ← -l = list user's crontab
crontab -u USER -l
crontab -e ← -e = edit user's crontab
crontab -u USER -e
at queue jobs for later execution echo "/sbin/shutdown -h now" |at 21:00 02/30/2009
at -t 200902302100
atq lists the user's pending jobs atq
atrm delete jobs for later execution atrm JOBID
watch execute a program periodically, showing output fullscreen watch ntpq -p ← By default, the program is run every 2 seconds
watch -n 1 ntpq -p ← 1 seconds interval
-d : highlight the differences between successive updates

etc

alias Alias with no arguments or with the -p option prints the list of aliases
When arguments are supplied, an alias is defined for each name whose value is given.
alias ← check all alias
alias ls='ls -la --color=auto'
alias grep='grep --color'
unalias Remove each name from the list of defined aliases.
If -a is supplied, all alias definitions are removed.
unalias COMMAND
ntpdate set the date and time via NTP ntpdate -b -u IP
-b : Force the time (step mode)
-u : If you are running ntpd, “-u” must be added.
chronyc command-line interface for chronyd chronyc sources
chronyc sources -v
chronyc sourcestats ← check offset
chrony makestep ← Correct the time
ntpq standard NTP query program ntpq -p
-p : Print a list of the peers known to the server
watch -n 1 ntpq -p
hwclock query and set the hardware clock (RTC) hwclock (-r) ← Read the Hardware Clock and print the time on standard output.
hwclock -w ← Set the Hardware Clock to the current System Time.
hwclock -s ← Set the System Time from the Hardware Clock.
man an interface to the on-line reference manuals man COMMAND
whatis display manual page descriptions whatis KEYWORD
whatis cat
whatis vi
history GNU History Library history |less
history 5 ← lists only the last 5 lines.
HISTSIZE=1000
HISTTIMEFORMAT=“%Y/%m/%d %H:%M:%S ”
which locate a command which ls
which -a bash ← -a : print all matching pathnames of each argument
time time a simple command or give resource usage time sleep 5
strace trace system calls and signals strace -t php test.php
strace -t -o test.txt php test.php
-t : each line of the trace with the time of day.
ltrace A library call tracer lltrace -o test.txt wget http://example.com/
ltrace -p PID
ltrace -p 3365
script make typescript of terminal session script -afq $LOG

Files and Directories Commands

File Commands

ls list directory contents ls -ltrh ← -r : reverse order while sorting
-h : with -l, print sizes in human readable format
ls -ltrh |less
cp copy files and directories cp -p SRC DES
cp -pi /etc/hosts{,.`date '+%Y%m%d'`}
cp -pr SRC/ DES/ ← -r,-R : copy directories recursively
cp -f SRC DES ← -f, --force
mv move (rename) files mv file1 file2
mv dir1 dir2
mv file1 file2 file3 DIR
rename renames multiple files rename .htm .html *.htm ← frm .htm to .html
rename "" test *.txt ← add test
rename test "" *.txt ← delete test
rm remove files or directories rm -rf TARGET ← -r,-R : remove directories
touch change file timestamps touch file1
touch -d “2017/10/20 13:00:00” file1
ln make links between files ln -s SourceFile TargetFile
ln -s SourceFile
ln -s ../TargetFile #Create a symbolic link to this directory
unlink unlink DES
unlink TragetFile
wc print newline, word, and byte counts for each file wc -l ← -l, --lines = print the line counts
tree list contents of directories in a tree-like format tree -Dpuga /etc
col filter reverse line feeds from input man ifconfig | col -bfx > test.txt

Directory Commands

pwd print name of current/working directory pwd
cd Change the current directory cd ← go to home directory
cd ~/ ← go to home directory
cd .. ← go to parent directory
pushd Adds a directory to the top of the directory stack pushd /var/log
pushd `pwd`
pushd +2 ← check pushd directory with dirs -v and go to No.2
pushd +3 ← check pushd directory with dirs -v and go to No.3
popd Removes entries from the directory stack. popd
dirs displays the list of currently remembered directories. dirs -v
mkdir make directories mkdir -p /tmp/test1/test2/ ← make parent directories as needed
mkdir -m 700 /home/user01/.ssh
rmdir remove empty directories
If you want to delete directory, you must use “rm -r DIR”.
rmdir DIR

Commands to Access File Contents

more file perusal filter for crt viewing
less opposite of more crontab -l |less
view Start in read-only mode.
cat concatenate files and print on the standard output cat /dev/null > access.log
tail output the last part of files tail -n 50 aaa.txt ← output the last N lines
tail -f /var/log/messsages
tailf follow the growth of a log file tailf /var/log/messages
tailf -n 50 aaa.txt
head output the first part of files head -n 100 aaa.txt ← -n , --lines
head * |more ← View the beginning of the file in the directory.
diff compare files line by line diff --suppress-common-lines --side-by-side File1 File2
diff /etc/test{,.`date '+%Y%m%d'`}
diff -r dir1 dir2 ← When comparing directories, recursively compare
sdiff side-by-side merge of file differences sdiff -s File1 File2 ← -s : Do not print common lines.
sdiff -s -w 200 File1 File2
colordiff
vimdiff vimdiff file1 file2
vim -d file1 file2

Searching

grep print lines matching a pattern grep WORD FILE |less
grep -Ev "^#|^$" xxx.txt
grep -Ev "^$|^#|^\s*#" file.txt
grep . ifcfg-eth* ← check filename and contents
grep "" ifcfg-eth* ← check filename and contents
grep -r PATTERN --include="*.txt" DIRECTORY ← -r : recursive
grep -r PATTERN DIRECTORY 2> /dev/null ← -r : recursive
egrep egrep is the same as grep -E egrep "aaa|bbb" file
find , xargs search for files in a directory hierarchy find . -name "*txt*"
find /dir -type f -name "*.log*" -mtime +7 -exec rm -rf {} \;
← “-mtime +7” is 7 days ago
find /etc -type f |xargs grep "xxxxx" 2> /dev/null
fd

File Compression

tar The GNU version of the tar archiving utility
tar warn the order of target and destination.
tar zcvf test.tar.gz Dir ← Create, Verbose, File
tar ztvf test.tar.gz ← Test, Verbose, File
tar zxvf test.tar.gz ← eXtract, Verbose, File
tar jcvf test.tar.bz2 DIR ← Create, Verbose, File
tar jxvf test.tar.bz2
tar zcvf /tmp/user01.tar.gz user01
tar zxvf user01.tar.gz -C /home # cd /home; tar zxvf user01.tar.gz
gzip
gunzip
compress or expand files gzip file1
gunzip file1.gz
gzip access_log.2011-[0][5-8]*.txt ←wild card
compress
uncompress
package and compress (archive) files compress file1
uncompress file1.Z
bzip2
bunzip2
bz2cat
a block-sorting file compressor bzip2 file1
bunzip2 file1.gz2
bz2cat file1.gz2
zip
unzip
package and compress (archive) files zip file.zip file1 file2
zip -l file.zip ← -l = list for check
unzip file.zip
unzip -t file.zip ← -t = test
lha lha a file.lzh file1 file2
lha t file.lzh
lha x file.lzh
gzcat gzcat file.gz
gzcat file.Z
zcat zcat file.Z
zless file perusal filter for crt viewing of compressed text zless file.gz
zgrep search possibly compressed files for a regular expression zgrep PATTERN file.gz
zegrep search possibly compressed files for a regular expression zegrep “new” test.txt.gz
zdiff compare compressed files zdiff file1.gz file2.gz

Character

lv a Powerful Multilingual File Viewer / Grep
qkc
nkf Network Kanji Filter [to utf8] nkf -w -Lu --overwrite test.txt
[to euc] nkf -e -Lu --overwrite test.txt
[to sjis] nkf -s -Lw --overwrite test.txt
find . -type f -name "*sh*" -print0 | xargs -0 nkf --overwrite -w -Lu
iconv Convert encoding of given files from one encoding to another iconv -f utf-8 -t sjis test.utf8 > test.sjis

User Administration

User

useradd create a new user or update default new user information Adminuser on RHEL
useradd -G wheel USER1
Adminiuser on Ubuntu
useradd -m -s /bin/bash -G sudo USER2
useradd -u UID -g GROUP -G GROUP1,GROUP2 -s /bin/bash -d HOME_DIR LOGIN
useradd -D ← check Default Parameter
adduser add a user to the system
whoami print effective userid whoami
w Show who is logged on and what they are doing. w
who show who is logged on who
who --all
userdel delete a user account and related files userdel -r USER
← (-r, --remove : Files in the user's home directory will be removed)
vipw edit the password, group, shadow-password or shadow-group file vipw ← edit /etc/passwd
vipw -s ← edit /etc/shadow
passwd change user password passwd
passwd user1
passwd -d user01 ← delete password
echo "password01" | passwd --stdin user01
————— Password Lock —————
passwd -S user1 ← check about the status of the password
passwd -l user01 ← Lock the user
passwd -u user01 ← Unlock
chpasswd update passwords in batch mode echo 'user01:password' | chpasswd
echo 'USER:PASS' > tmp.txt ; chpasswd < tmp.txt ; rm -f tmp.txt
mkpasswd Command to create password for RHEL.
If there is no mkpasswd command, install expect
mkpasswd -l 15 ← Generate 15-character password
pwgen Command to create password for Ubuntu and Mac. pwgen -s 15 1 ← Generate one 15-character password
chage change user password expiry information chage -l USER ← check
chage -M 90 USER ← the password expires day set 90days
change -d 0 USER ← force a user to change their password at next login
usermod modify a user account usermod -g GROUP USER
usermod -g GROUP -G SUBGROUP USER
usermod -G SUBGROUP USER
usermod -aG SUBGROUP USER ← add Group
usermod -G SUBGROUP1,SUBGROUP2 USER
usermod -G "" USER
usermod -l USER_NAME_NEW USERNAME_OLD ← change username
usermod -d HOME_DIR_NEW USER_NAME ← change home directory
usermod -u UID USER ← change UID
chsh change login shell chsh -l ← = cat /etc/shells
chsh -s /bin/bash ← changing shell
chsh -s /bin/bash user01
getent get entries from Name Service Switch libraries getent passwd ← you can check LDAP Users
getent group
getent shadow
pam_tally2 The login counter (tallying) module
Up to RHEL 7
pam_faillock replaces pam_tally2.
pam_tally2 -u USER ← check
pam_tally2 -u USER --reset ← reset
faillock Tool for displaying and modifying the authentication failure record files
RHEL 8 or later
pam_faillock replaces pam_tally2.
faillock --user USER ← Check how many times you made a mistake in your password
faillock --user USER --reset ← Reset incorrectly entered passwords

Group

groups print the groups a user is in groups
groups USERNAME
groupadd create a new group groupadd -g GID GROUP
groupadd -g 1100 dev
addgroup add group to the system addgroup [--gid ID] group
groupdel delete a group groupdel GROUP
gpasswd gpasswd -a USER sudo ← add USER to GROUP
gpasswd -r USER sudo ← remove USER from GROUP
groupmod change USER's GID groupmod -g GID GROUP
groupmod -g 1501 testgroup1
find / -gid OLDGID -print ← Check the OLD GID
Reference
usermod -aG SUBGROUP USER ← add Group
chgrp change the Group of the file chgrp -R GROUP FILE
vigr edit the password, group, shadow-password or shadow-group file

File Permissions

chmod change file mode bits chmod 777 TARGET
chmod u+s PROGRAM ← add SSUID(Set User ID)
chown change file owner and group chown USER FILE
chown USER:GROUP FILE
chown -R USER:GROUP DIR ← -R : operate on files and directories recursively

Etc

finger user information lookup program finger
finger user01
finger -l user01
su change user ID or become superuser su - ← change root user
sudo su - USER -s /bin/bash
su - user1 -c "ssh user1@192.168.0.xx ls -lh /tmp" >> aaa.txt
sudo execute a command as another user sudo su -
sudo -i
sudo -u USER COMMAND
sudo sh -c 'echo "test" >> /tmp/test.txt'
sudo -l ← Displays prohibited commands
id print real and effective user and group IDs id USERNAME
last show listing of last logged in users last
last -5 ← last 5 logged in users
last USER
lastlog reports the most recent login of all users or of a given user lastlog
umask set file mode creation mask umask ← check
umask 022 ← default 666-022=644(rw-r–r–)
umask 002 ← 666-002=664(rw-rw-r–)
umask 000 ← 666-000=666(rw-rw-rw-)

Network

Network

ip show / manipulate routing, devices, policy routing and tunnels ip a ← print ip address
ip addr ← print ip address
ip r ← Show IP Routing
ip route ← Show IP Routing
ss another utility to investigate sockets ss -lt ← List all Listening TCP Connections
ss -ua ← List all UDP Connections
ss -ltp ← Process Name with Listening TCP
ss -anu
netstat Print network connections, routing tables, interface statistics, masquerade connections, and multicast memberships netstat -anp (-a : Show both listening and non-listening sockets.)
netstat -rn (-r : Display the kernel routing tables.)
ifconfig configure a network interface ifconfig ← check ip
ifconfig -a ← -a : display all interfaces
ifconfig eth0 up
ifconfig eth0 down
ifdown take a network interface down ifdown eth0
ifdown eth0 && ifup eth0
ifup bring a network interface up ifup eth0
ifdown eth0 && ifup eth0
route show / manipulate the IP routing table route ← show the IP routing table
route -n ← show the IP routing table
route add -net 192.168.10.0 netmask 255.255.255.0 gw 10.50.0.1
route add -host 192.168.0.100 gw 192.168.1.100
route del -net 192.168.10.0 netmask 255.255.255.0
ethtool Display or change ethernet card settings ethtool eth0
ethtool -s eth0 speed 100 duplex full autoneg off
ethtool -s eth0 autoneg on
mii-tool view, manipulate media-independent interface status mii-tool eth0
mii-tool -vv eth0
arp manipulate the system ARP cache arp -n
arp -an ← (-a : Shows the entries of the specified hosts.)
arp -d 192.168.xx.xx ← delete arp
nmcli line tool for controlling NetworkManager nmcli d #d=device
nmcli d show ← defail
nmcli c #c=con=connection
nmcli c down eno1
nmcli c up eno1
nmtui
tcpdump dump traffic on a network tcpdump -n port 80 -i any
tcpdump -n not arp and not port 123 and not port 22
tcpdump host 192.168.0.10 -n -w /tmp/20110615.pcap
tcpdump -r /tmp/20110615.pcap ← -r : Read packets from file
tcpdump -D # NIC LIST

Check Nectork Connection

ping send ICMP ECHO_REQUEST to network hosts ping -c 5 -s 1500 192.168.0.1 ​
ping -i 0.5 192.168.0.1 # -i : interval
traceroute print the route packets trace to network host traceroute -n 192.168.0.10
traceroute -T -p 80 192.168.0.10 ← (-T = TCP)
traceroute -U -p 53 192.168.0.10 ← DNS (-U = UDP)
tracepath traces path to a network host discovering MTU along this path tracepath -n 192.168.0.10 ← UDP
*tracepath don't use TCP.
mtr a network diagnostic tool mtr --tcp -P 80 xxxxxx
mtr --udp -P 53 xxxxxx
mtr -rwb xx.xx.xx.xx -c 10 -T -P 443
nmap Network exploration tool and security / port scanner nmap google.com ← Check TCP
nmap -sT -sU -Pn x.x.x.x ← check TPC and UDP
nmap -Pn -sT -p 22 xx.xx.xx.xx ← check Firewall
nmap -Pn -sT -p 22 xx.xx.xx.xx/24 ← check Firewall
nmap -sU -p 161 xxxxxx ← Check UDP
nmap -Pn -p 22 HOST
nmap -p 443 www.google.com
nc
netcat
Concatenate and redirect sockets nc 192.168.0.10 80 22 ← check TCP
nc -u 192.168.0.100 53 ← check UDP
nc -vz 192.168.0.10 1-1023 ← portscan
nc -v x.x.x.x 22 < /dev/null > /dev/null 2>&1 || echo NG
nping nping --tcp -p PORT HOST
nping -c 1 --tcp -p PORT HOST
httping measure the latency and throughput of a webserver
http_ping
hping , hping3
fping fping -g 192.168.0.0/24

DNS

dig DNS lookup utility dig -h ←help
dig [@global-server] [domain] [q-type]
dig @8.8.8.8 google.com any
dig @8.8.8.8 -x 74.125.235.101
dig google.com mx
dig +trace google.com
dig +trace -x 173.252.120.6
nslookup query Internet name servers interactively nslookup -type=any google.com 8.8.8.8
nslookup google.com 8.8.8.8
nslookup -type=txt google.com
host DNS lookup utility host ← help
host [-t type] [server]
host gmail.com
host x.x.x.x
host -t any google.com 8.8.8.8
host -t mx gmail.com 8.8.8.8
host -t soa gmail.com
-t = specifies the query type
whois client for the whois service whois google.com
nscd name service cache daemon nscd --help
nscd -i hosts ← chache clear
nscd -g ← Print current configuration statistics

Connection

telnet user interface to the TELNET protocol telnet IP PORT
curl -v telnet://<host>:<port>
ssh popular OpenSSH SSH client (remote login program) ssh USER@IP
ssh xx.xx.xx.xx "hostname; netstat -rn |grep 10.110.0"
ssh xx.xx.xx.xx sudo /sbin/reboot
ssh -o "StrictHostKeyChecking no" xx.xx.xx.xx
scp secure copy (remote file copy program)
the link file copyed as the real file.
scp test.tar.gz user1@192.168.0.10:/tmp
scp -rp /home/user1 user1@192.168.0.10:/home
scp -rp /tmp/test1/ user1@192.168.0.10:/tmp/test2/
rsync popular a fast, versatile, remote (and local) file-copying tool
the link file copyed as the link file.

rsync -avzh --stats --delete /home/user1/ /tmp/user1.bk/
rsync “/” is very important.
rsync -e ssh -avzh --stats --delete /home/user1/ user2@192.168.0.2:/home/backup/server1/home/user1/
rsync -e ssh -avzh --stats –-bwlimit=1250 FILE user@192.168.0.2:/DIR/ # 1Mbps = 125KBps
ssh-keygen authentication key generation, management and conversion ssh-keygen -t rsa ← generate rsa key pair
ssh-keygen -t rsa -b 4096 -C "" -N "" -f id_rsa
ssh-keygen -R HOST
← Removes all keys belonging to hostname from a known_hosts file.
sshpass sshpass -p “XXXXXX” ssh x.x.x.x
ssh-copy-id use locally available keys to authorise logins on a remote machine
ssh-copy-id USER@x.x.x.x
ssh-copy-id -i xxxxx USER@x.x.x.x
Other method
cat ~/.ssh/id_rsa.pub | ssh USER@x.x.x.x "mkdir -p ~/.ssh; cat >> ~/.ssh/authorized_keys"

HTTP

curl popular transfer a URL curl -O http://example.com/images/test.jpg
curl -I http://www.example.com/ ← Only Header
curl -i http://www.example.com/ ← Header and Body
curl --proxy http://proxy.example.com:8080 http://example.com/
curl -v telnet://<host>:<port>
wget The non-interactive network downloader. wget http://google.com/
wget -e http_proxy=xx.xx.xx.xx:8080 http://example.com/
wget -e https_proxy=xx.xx.xx.xx:8080 https://example.com/
wget -S --spider http://example.com/ ← Only Header

FTP

ftp ARPANET file transfer program
lftp Sophisticated file transfer program
sftp OpenSSH secure file transfer echo "ls -lt" | sftp -b - user@host <- -b : batch mode

SNMP

snmpwalk retrieve a subtree of management values using SNMP GETNEXT requests snmpwalk -v 2c -c public localhost sysname
snmpwalk -v 2c -c public localhost .1.3.6.1.2.1
snmpget communicates with a network entity using SNMP GET requests snmpget -v 2c 192.168.0.10 -c public .1.3.6.1.4.1.2021.11.50.0
snmptranslate translate MIB OID names between numeric and textual forms snmptranslate -Tp | less
snmpnetstat display networking status and configuration information from a network entity via SNMP snmpnetstat -v 2c -c public -Can localhost
snmpnetstat -v 2c -c public -Ci localhost
snmpnetstat -v 2c -c public -Cs localhost

Shell Script

Shell

date print or set the system date and time date --date '10day ago' +"%Y%m%d" → 20061030
date +"%Y%m%d" → 20061030
date +"%H:%M" → 12:47
cp -p FILE FILE.`date +%Y%m%d`
cp -p FILE FILE.`date -d '1day ago' +%Y%m%d`
tr translate or delete characters
cut remove sections from each line of files echo abcdef |cut -c 3-
echo abcdef |cut -c 2-4
sort sort lines of text files sort -t: +1 -n sample.txt
uniq report or omit repeated lines cat access_log.1 | awk {'print $4'} |awk -F: {'print $1$2$3'} | sort |uniq -c
logger a shell command interface to the syslog(3) system log module logger "test test"
tee read from standard input and write to standard output and files xxxx.sh | tee xxxx.log
xxxx.sh | tee -a xxxx.log
xxx.sh 2>&1 | tee xxxx.log ← Save standard output and standard error output to file
basename strip directory and suffix from filenames SHELLNAME=`/usr/bin/basename $0`
SHELLNAME=`/usr/bin/basename $0 .sh`
dirname strip last component from file name DIR=`dirname ${0}`
paste merge lines of files paste -d, test1.txt test2.txt
awk echo "1 2 3 4 5" | awk '{ print $1 "," $3 }'
echo "1 2 : 3 4 : 5" | awk -F: '{ print $2 }'
sed sed -e 's/xxx/XXX/g' input.txt > output.txt
sed -i "s/IPADDR=192.168.0.10/IPADDR=192.168.0.11/g" ifcfg-eth0
mail
mailx
send and receive Internet mail
echo test | mail -s "test" -S "smtp=smtp://xx.xx.xx.xx:25" test@example.com
cat test.txt | mail -s "test" -S "smtp=smtp://xx.xx.xx.xx:25" test@example.com
echo "`hostname` `date`" | mail -s "attach test" -a tmp.txt -S smtp=smtp://x.x.xx:25 -r from@example.com to@test.com
while while : ; do uptime ; sleep 1 ; done
while : ; do uptime >> /tmp/tmp.txt ; sleep 1 ; done
while : ; do ps aux |grep httpd |wc -l ; sleep 1 ; done
for for i in 127.0.0.1 192.168.10.1; do ping -c 2 $i; done
sleep sleep 1
usleep sleep some number of microseconds usleep 1000000 ← 1,000,000 = 1sec
usleep 100000 ← 100,000 = 0.1sec
usleep 10000 ← 10,000 = 0.01sec

Hardware

Hardware

dmesg print or control the kernel ring buffer dmesg
dmesg -H -P -T
(-H = --human)(-P = --nopager)(-T = --ctime)
The dmesg time is incorrect.
Timestamps are slowed down because the time the kernel was asleep is lost.
lsusb List USB devices lsusb
lspci list all PCI devices lspci
nproc print the number of processing units available nproc
grep -c processor /proc/cpuinfo
getconf _NPROCESSORS_ONLN
inxi Display info about all hardware inxi -Fxz
hwinfo Display info about all hardware hwinfo
hwinfo --short
lshw Display info about all hardware
“lshw” stands for “List Hardware”.
lshw -short
lshw -C cpu <- Display all CPU info
lshw -short -C memory
lshw -short -C disk
lshw -C network
lscpu Display all CPU info lscpu
dmidecode dmidecode -t memory | grep -i size
dmidecode -t memory | grep -i max <- Show maximum memory for the hardware
dmidecode -t bios <- Display UEFI/BIOS info

Module

lsmod show the status of modules in the Linux Kernel lsmod
modinfo show information about a Linux Kernel module modinfo MODULENAME
modinfo bnx2
insmod insert a module into the Linux Kernel
rmmod remove a module from the Linux Kernel
modprobe add and remove modules from the Linux Kernel

Disk Utilities

HDD

du estimate file space usage du -sh *
du -sh dir/
du -h --max-depth=1
fuser identify processes using files or sockets fuser -mv /mnt/test ← check
fuser -mvk /mnt/test ←(-k : Kill processes)
chroot run command or interactive shell with special root directory
hdparm get/set hard disk parameters
dumpe2fs dump ext2/ext3/ext4 filesystem information
badblocks search a device for bad blocks

Partition

df report file system disk space usage df -h ← (-h : print sizes in human readable format)
df -BG ← Bigabyte Unite
df -BM ← Megabyte Unite
sfdisk partition table manipulator for Linux sfdisk -l ←(-l : List the partitions of a device.)
fdisk manipulate disk partition table fdisk -l ← ( -l : List the partition tables)
fdisk -l /dev/sdb
fdisk -l -o +UUID
gdisk Interactive GUID partition table (GPT) manipulator
parted a partition manipulation program parted -l ← check partitions
parted /dev/mapper/mpath0
lsblk list block devices lsblk
e2label Change the label on an ext2/ext3/ext4 filesystem

Swap

mkswap set up a Linux swap area
swapon enable devices and files for paging and swapping swapon -s ← Check
swapon -a
swapon /dev/xvda3
swapoff disable devices and files for paging and swapping swapoff -a

File Systems

mkfs build a Linux filesystem
#you must umount the device before mkfs.
mkfs -t xfs /dev/sdb1
mkfs -t ext3 /dev/sdb1
mkfs -t ext4 /dev/sdb1
mkfs.xfs mkfs.ext4
mkfs.ext3
#you must umount the device before mkfs. mkfs.ext4 /dev/sdb1
mkfs.ext3 /dev/sdb1
mkfs2fs create an ext2/ext3/ext4 filesyste
#you must umount the device before mkfs.
mke2fs /dev/sdb1 ← ext2
mke2fs -j /dev/sdb1 ← ext3
xfs_info xfs_info /dev/sda1
tune2fs adjust tunable filesystem parameters on ext2/ext3/ext4 filesystems tune2fs -l /dev/mapper/mpath0
← -l : List the contents of the filesystem superblock.
tune2fs -l /dev/mapper/mpath0 |egrep "count|interval"
tune2fs -i 0 -c 0 /dev/mapper/mpath0
← -i : interval, -c : mount count
fsck check and repair a Linux filesystem
you must umount the device before fsck.
for example single usermode and umount.

'shutdown -r -F now' is force fsck after reboot.
fsck -p /dev/sda1
← -p : Automatically repair (“preen”) the file system.
fsck.ext4 check and repair a Linux filesystem
e2fsck check a Linux ext2/ext3/ext4 file system
resize2fs ext2/ext3/ext4 file system resizer resize2fs /dev/testvg/lvol0

Data

dd convert and copy a file dd if=/dev/zero of=test_10M bs=1M count=10
dd if=/dev/zero of=test_100M bs=1M count=100
dd if=/dev/zero of=test_1G bs=1M count=1000
dd if=/dev/zero of=temp.bin bs=1 count=0 seek=1G ← sparse file
sync flush file system buffers
shred overwrite a file to hide its contents, and optionally delete it

mount

mount mount a filesystem mount
mount | column -t
mount /mnt/test /dev/sda1
mount -o remount /dev/sda1
mount -t cifs //xx.xx.xx.xx/test /mnt/test -o username=guest,password=
umount unmount file systems umount /mnt/test
umount -f /mnt/test
(-f : Force unmount(in case of an unreachable NFS system))
umount -l /mnt/test
(-l : Lazy unmount.Detach the filesystem from the filesystem hierarchy now )

LVM

References : LVM - How to Use LVM in Linux

LVM

lvm LVM2 tools

PV (Physical Volume)

pvs report information about physical volumes
pvdisplay display attributes of a physical volume pvdisplay
pvdisplay -C
pvcreate initialize a disk or partition for use by LVM pvcreate /dev/mapper/mpath0p1
pvcreate /dev/mapper/mpath0p1 /dev/mapper/mpath1p1
pvremove remove a physical volume pvremove /dev/mapper/mpath0p1
pvscan scan all disks for physical volumes

VG (Volume Group)

vgs report information about volume groups vgs -o +vg_tags ← check tag
vgdisplay display attributes of volume groups vgdisplay
vgdisplay -C
vgcreate create a volume group vgcreate vgdata1 /dev/hdb1 /dev/hdc1
vgremove remove a volume group vgremove vg01
vgscan scan all disks for volume groups and rebuild caches
vgchange change attributes of a volume group vgchange -a y ← activate
vgchange -a n ← deactivate
vgchange -a y vg01
vgchange -a n vg01
Check : lvdisplay VGDATA |grep Status
vgchange --addtag $(uname -n) VG_TEST
vgchange --deltag $(uname -n) VG_TEST
vgextend add physical volumes to a volume group vgextend vg01 /dev/hdd1
vgrename rename a volume group vgrename oldvg newvg

LV (Logical Volume)

lvs report information about logical volumes
lvdisplay display attributes of a logical volume lvdisplay
lvdisplay -C
lvdisplay /dev/mapper/VGDATA-lv00
lvcreate create a logical volume in an existing volume group lvcreate -l PENUMBER vgdata
lvcreate -L 150G vgdata
lvremove remove a logical volume lvremove /dev/testvg/lvol0
lvscan scan (all disks) for logical volumes
lvresize resize a logical volume lvresize -L +5G /dev/vg0/home
lvextend extend the size of a logical volume lvextend -L +5G /dev/vg0/home
lvextend -l +100%FREE /dev/mapper/Array00-lv00
lvreduce reduce the size of a logical volume
lvrename rename a logical volume lvrename /dev/vgdata/lvol0 /dev/vgdata/lvol1

Performance

Performance

top display Linux processes top -b -n 4 -d 5 ← interval 5sec , 4 times
sar Collect, report, or save system activity information. sar -f /var/log/sa/sa16
sar (cpu,io)
sar -r (memory)
sar -q (Loadaverage)
vmstat LIKE Report virtual memory statistics vmstat 1 ← interval 1sec (cpu, io, memory, swap)
vmstat 1 5 ← interval 1sec, 5 times (cpu, io, memory, swap)
iostat Report Central Processing Unit (CPU) statistics and input/output statistics for devices and partitions. iostat -xtk 1 (cpu, io) ← interval 1sec
mpstat Report processors related statistics. mpstat -P ALL
uptime Tell how long the system has been running. while : ; do uptime ; sleep 1 ; done
while : ; do uptime » /tmp/tmp.txt ; sleep 1 ; done
w Show who is logged on and what they are doing.
free Display amount of free and used memory in the system free -m ← show output in MB
iotop simple top-like I/O monitor iotop -b -n 4 -d 15 ← interval 15sec , 4 times
dstat LIKE versatile tool for generating system resource statistics dstat -taf

Load Test

fio

Software

Software

make GNU make utility to maintain groups of programs
patch apply a diff file to an original patch -p1 -N < ../xxx.patch
ldd print shared library dependencies ldd BINARY
dnf popular an interactive, rpm based, package manager dnf repolist ← check enabled repository
dnf search STRINGS
dnf info PACKAGE ← check rpm version etc
dnf install PACKAGE
dnf --disablerepo=* --enablerepo=test-repo repolist
yum popular an interactive, rpm based, package manager yum repolist ← check enabled repository
yum search STRINGS
yum info PACKAGE ← check rpm version etc
yum install PACKAGE
yum --disablerepo=* --enablerepo=test-repo repolist
rpm RPM Package Manager rpm -ivh PACKAGE.rpm ← install
rpm -e PACAGE.rpm ← uninstall
rpm -qa --last
apt apt provides a high-level commandline interface for the package management system. apt list --installed ← check installed package
dpkg dpkg -l ← check installed package
alien alien -d package-x.x.x.rpm
alien -r package-x.x.x.deb
update-alternatives update-alternatives --config mta
rhn_register rhn_register --nox --proxy=http://192.168.0.10:9999

etc

X Window System

startx initialize an X session startx
xhost server access control program for X xhost + ← Access is granted to everyone
xauth X authority file utility

TUI

ntsysv simple interface for configuring runlevels
authconfig-tui an interface for configuring system authentication resources
system-config-securitylevel
system-config-network-tui

etc

md5sum compute and check MD5 message digest find . -type f -exec md5sum {} \; > /tmp/md5.out
← check all files
gpg OpenPGP encryption and signing tool
screen
kermit





References