Linux Commands

Linux Commands Cheat Sheet

Hello everyone, here is a list of all the linux commands I can think of and can be helpful for your usage.

Input/output
echo
It is used to print string values in the terminal.

Examples:

echo "Hello World" #Print with a newline
echo -n "Hello World" #Print without a newline
echo -e "Hello\tWorld" #Print with tab space
printf
It is used to print formatted string values in the terminal.

Examples:

printf "Hello World" #Print without a newline
printf "Hello World\n" #Print with a newline
printf "The price of the book is %0.2f\n" 56.856 #Print the formatted data
read
It is used to take input from the user.

Examples:

read variable #Take single input
read variable1, variable2, variable3 #Take multiple inputs
read - p "enter your name: " variable #Take input with prompt
read - sp "enter password: " variable #Take secret input
read - t 5 - p "Enter your pin : " pin_number #Take input with time limit
read - n 11 mobile #Take input of maximum length
pipe
It is used to take the output of one process and pass it as the input for another process. The symbol, ‘|’ is for the pipe.

Example:

# The output of`echo` command will be sent as the input of the`wc` command
echo "Hello World" | wcw
Redirection
The redirection is used in Linux to change the standard input/output of the device after executing the command. The ‘<’ symbol is used for input redirection and the ‘>’ symbol is used for output redirection.

Examples:

ls - l > folderList.txt #Redirect output
ehco "test" 2 > error.txt #Redirect error into the file
ehco "test" 2 >& 1 error.txt #Redirect error into the file and the terminal
cat > myfile.txt < folderList.txt #Redirect input data from one file to another file
System Information
date
It is used to print the current date and time of the system in different formats.

Examples:

date #Print current date and time without formatting
date +%m-%d-%Y #Print the current date
date +%H:%M:%S #Print the current time
date +"%A, %B %d,%Y" #Print the current date with weekday and month name
hostname
It is used to check or modify the hostname, domain, and IP address.

Examples:

hostname #Display the hostname
hostname -d #Display the domain name
hostname -I #Display the IP address
hostname -b new_hostname #Set the new hostname
uname
It is used to print different information about the hardware and the operating system.

Examples:

uname #Print the kernel name
uname –n #Print the hostname
uname –m #Print the hardware name
uname -o #Print the operating system name
uname –a #Print all information related to hardware and OS
vmstate
It is used to get information about the memory, disk, processes, block IO, paging, and CPU scheduling.

Examples:

vmstat –a #Display the active and inactive memory of the system
vmstat –f #Display the number of forks since boot
vmstat -s #Display event counter and memory statistics
vmstat -d #Display disk statistics
iostate
It is used to monitor the statistics of the system input/output of devices and partitions. The sysstat package requires to install before using this command.

Examples:

Iostat #Print all statistics and report
Iostat -c #Print the statistic information of CPU
Iostat -d #Print the device report
Iostat -x #Print the statistics information in details
Iostat -k # Print the statistic in KB or MB
Iostat -p #Print the statistics information of block devices
Iostat -N #Print the statistics information of lvm2
free
It is used to print the detailed report of the system’s memory usage.

Examples:

free #Print the output in the default format
free -h #Print the output in human-readable format
free -b #Print the output in bytes
free -k #Print the output in KB
free -g #Print the output in GB
whoami
It is used to print the name of the currently logged-in user.

Example:

whoami #Print the logged-in user's name
uptime
It is used to print the information about the total running time of the system.

Examples:

uptime #Print the uptime in the default format
uptime -p #Print the uptime in pretty format
uptime –s #Print the time since the system is up
shutdown
It is used to power off or shutdown or restart the system from the terminal.

Examples:

shutdown #Shutdown normally
shutdown –h 0 #Shutdown immediately
shutdown –r #Shutdown and restart
shutdown –r now #Shutdown and restart immediately
shutdown –c #Shutdown can be canceled
reboot
It is used to reboot the system from the terminal with root privilege.

Example:

sudo reboot #Reboot the system
User Management
adduser
It is used to add a new user account in the Linux system. The root privilege requires to execute this command.

Examples:

#Create a new user information in default location
sudo adduser username
#Create a new user information in the specified location
sudo adduser username --home /home/temp/
deluser
It is used to remove the Linux user account. The root privilege requires to execute this command.

Examples:

sudo deluser username #Delete user
sudo deluser --remove-home username #Delete user with home directory
sudo deluser –force #Delete user forcefully
sudo deluser --backup-to /backupUser username #Delete user keeping backup files
usermod
It is used to modify the information of any existing Linux user. It requires root privilege to execute.

Examples:

sudo usermod --login newUsername oldUsername #Change the username
sudo usermod --uid newID username #Change the ID of an existing user
sudo usermod --gid groupname username #Change the group name of an existing user
groupadd
It is used to create a new group. It requires root privilege to execute this command.

Examples:

#Create a new group
sudo groupadd groupname
#Create a group forcefully if it already exists
sudo groupadd –f groupname
#Create a new group with a particular group id
sudo groupadd -g 6723 groupname
#Create a new group by defining the range of group id
sudo groupadd -K GID_MIN=4000 -K GID_MAX=5000 groupname
groupdel
It is used to delete an existing group. It requires root privilege to execute this command.

Examples:

sudo groupdel groupname #Delete the group name
sudo groupdel –f groupname #Delete the group forcefully
groupmod
It is used to modify any existing group. It requires root privilege to execute this command.Examples:

sudo groupmod -n newGroupname Groupname #Change the group name
sudo groupmod -g 676 Groupname #Change the group id
last
It is used to print the information about the last login session of the Linux users.

Examples:

last #Print all last login session information
last username #Print the last login session information of a user
last -10 #Print the last 10 login session
last –p 2022-01-01 #Print the last login session information of a specific date
id
IT is used to search the username, group name, and the ID of the current user or another user of the server.

Examples:

id #Print the ID and group information related to the current login user’s
id username #Print the ID and group information related to the particular user
id -u username #Print the user ID of the particular user
id -g username #Print the group ID of the particular user
groups
It is used to print the primary and supplementary group names for each username or the current process if no username is given.

Examples:

Groups #Print the group information of the current login user
groups username #Print the group information of the specific user
groups username1 username2 #Print the group information of the multiple users
passwd
It is used to change the user’s password. The root user can change the password of all users and other users can change their password only.

Examples:

passwd #Change the password of the current login user
sudo passwd username #Change the password of any user with root privilege
sudo
It is used to perform the restricted tasks with the root privileges without logging as root user or by logging as the root user.

Examples:

sudo apt-get update #Update the current system
sudo -i #Login as the root user
sudo bash #Run bash as the root user
sudu !! #Execute the last command with the root privilege
su
It is used to switch from the current user to another user.

Example:

su username #Switch to another user without changing the home directory
su -l username #Switch to another user by changing the current directory
su -p username #Switch to another user by preserving the environment variables
Packages
apt
It is used to install, update, delete and manage different packages in Linux operating system. It requires root privileges.

Examples:

sudo apt update #Update the installed packages
sudo apt upgrade #Upgrade the installed packages
sudo apt upgrade packagename #Upgrade specific package
apt-get
It works like the `apt` command but some commands are used differently by `apt-get` command when it is used in replacement of the `apt` command.

Examples:

sudo apt-get update #Update the packages
sudo apt-get dist-upgrade #Upgrade the packages with full dependencies
dpkg
It is used to install, remove, manage and query Debian packages and their dependencies. It requires root privilege to use.

Examples:

#Install the Debian package
sudo dpkg –i debian_package_name
#Print installed packages related to nano editor
sudo dpkg -l '*nano*'
#Remove vim editor
sudo dpkg -r vim
Disk Usage
du
It is used to get disk usage information.

Examples:

du #Print the disk usage information in the default format
du -h #Print the disk usage information in human-readable format
du -c #Print the disk usage information with total measurement value.
du -s #Print the summary of the disk usage information
du -a #Print disk usage information with the sizes of files and folders
df
It is used to print the used available disk space information of the file system.

Examples:

df #Print the used and available disk space in the default format
df -h #Print the used and available disk space in human-readable format
df -T #Print the used and available disk space with file system type
df --total #Print the used and available disk space with total values
df -a #Print the used and available disk space with other information
fdisk
It is used to create or modify the partition tables of the hard disk.

Examples:

fdisk -l #Print partition table of all devices
fdisk /dev/sdb #Run fdisk for the specific device
fdisk -l /dev/sda #Print the partition table list of a device
mount
It is used to attach the file system and removable devices at a particular mount point.

Examples:

sudo mount #Print all currently attached file system
sudo mount -t ext3 #Print the list of all ext3 file system
sudo mount /dev/sda1 /mnt/media #Mount a file system and a directory
unmount
It is used to detach the mounted file system and the device.

Examples:

sudo umount ext3 #Unmount ext3 file system
sudo umount /dev/sdb1 #Unmount sdb1 device
Process Management
ps
It is used to get information related to the processes of the system.

Examples:

ps #Print the process list of the current shell
ps -e #Print the list of all running process
ps -a #Print the list of the process that is not associated with the terminal
ps -T #Print the list of the process that is associated with the terminal
pgrep
It is used to search the process ID of the running program based on the specific condition.

Examples:

pgrep bash #Print the process ID
pgrep ssh -l #Print the process name with ID
pgrep -u root #Print the process list of a particular user
kill
It is used to send a signal to a process defined by a PID. The default signal is SIGTERM which terminates the process.

Examples:

kill –l #Print the available kill signals
kill 5645 #Terminate the process based on ID
kill -1 9078 #Reload the process based on the ID
kill –n 15 7845 8756 #Terminate multiple processes
killall
It is used to kill any running process forcefully based on the given process name.

Examples:

killall processname #Kill the process based on name
killall -i processname #Ask permission before killing the process
killall –u username #Kill process based on the username
pkill
It is used to send a signal to a process of the running program based on the full or partial process name, username, or other attributes.

Examples:

pkill firfox #Terminate a particular process
pkill -i gedit #Terminate a process in a case-insensitive manner
fg
It is used to move the background job of the current shell into the foreground.

Example:

fg %1 #Refer to the specific job number
fg %+ #Refer to the current job
fg %- #Refer to the previous job
bg
It is used to restart a stopped background process.

Example:

bg %1 #Refer to the specific job number
bg %+ #Refer to the current job
bg %- #Refer to the previous job
Scripting Tools
sed
It is used to search, find-replace, and insert or delete purposes.

Examples:

#Replace the word, 'World' with the word 'Everyone'
echo 'Hello World' | sed 's/World/Everyone/'
#Replace the word, 'book' with the word 'e-book'
sed 's/book/e-book/g' filename.txt
#Delete the 5th line of the file
sed '5d' filename.txt
awk
It is a scripting language that is used for manipulating data and generating a report by pattern scanning and processing.

Example:

awk '{print}' filename.txt #Print the content of the file
awk '/Linux/ {print}' filename.txt #Print those lines of the file that contains ‘Linux’
awk '{print $1,$4}' filename.txt #Print the first and fourth columns of the file
sort
It is used to sort the content of a file.

Examples:

sort filename.txt #Sort the string data in ascending order
sort –r filename.txt #Sort the string data in descending order
sort -n file1.txt #Sort the numeric data in ascending order
sort -o output.txt filename.txt #Redirect the sorted output of filename.txt to output.txt
wc
It is used to count the number of characters, words, and lines of a file or the standard input.

Examples:

echo "Hello" | wc –c #Count the total characters of the string
wcw filename.txt #Count the total words of a file
wc –l filename.txt #Count the total lines of a file
uniq
It is used to filter the duplicate lines of a file.

Examples:

uniq filename.txt #Print the file after filtering the duplicate lines
uniq –c filename.txt #Print the file after filtering the duplicate lines with number
uniq –d filename.txt #Print the duplicate lines of the file only.
uniq –u filename.txt #Print the unique lines of the file only
tr
It is used to convert the string or delete characters from the string.

Examples:

echo Linux | tr [:lower:] [:upper:] #Change all small letters to capital letters of the string
tr A-Z a-z < filename.txt #Change all capital letters to small letters of a file
echo "fool" | tr -c 'ool\n' 'b' #Change those characters by ‘b’ that don’t match with ‘ool\n’
File commands
touch
It is used to create an empty file and change the access or modification timestamp value of the existing file.

Examples:

touch filename #Create a blank file
touch file1, file2, file3 #Create multiple blank files
touch -a filename.txt #Modify the access time of an existing file
touch -m filename.txt #Modify the modification time of an existing file
cat
It is used to create, read, and concatenate files.

Examples:

cat > filename #Create a new file
cat filename #Print an existing file
cat filename1, filename2, filename3 #Print multiple files
cat -n filename #Print an existing file with the line number
cp
It is used to copy file or group of files or directories.

Examples:

cp file1.txt file2.txt #Copy the file1.txt to file2.txt
cp file1.txt file2.txt dirname #Copy multiple files into a directory
cp -i file1.txt file2.txt #Ask before overwriting the existing file
cp -f file1.txt file2.txt #Copy file forcefully
mv
It is used to move files and directories from one location to another location.

Examples:

mv filename1 filename2 #Move the file
mv dircetory1 directory2 #Move the directory
mv -i filename directory #Ask for overwriting before moving
rm
It is used to remove files and directories.

Examples:

rm filename #Remove a single file
rm file1, file2, file3 #Remove multiple files
rm -i filename #Ask before deleting
rm -r directory #Remove all files and folders of the directory recursively
rm -d directory #Remove empty directory
ln
It is used to create the symbolic link.

Examples:

ln -s filename #Create a link to a file
ln -s filename linkname #Create a link with the linkname
ln -sf filename linkname #Create a link forcefully if exists
less
It is used to read the large file or command output that displays the content of a file or a command output part by part to make the reading task faster.

Examples:

Less filename #Print the content of a file
ps aux | less #Print the command output
ps aux | less –N #Print the command output with line number
ps aux | less -p "root" #Highlight the word, root in the output
more
It works similar to `less` command and it has many other features to scroll the content of the large file or command output.

Examples:

more file.txt #Display the content of a file
more -d file..txt #Help user to navigate the content
more -p file..txt #Display the page after clearing the previous content
more -c file..txt #Display all pages in the same area
dmesg | more #Display the content of command output
cut
It is used to cut the portion of each line from a file and print the output in the terminal.

Examples:

cut -b 3 file.txt #Print the 3rd character from each line of the file
cut -c 2,5 file.txt #Print the 2nd and 5th characters from each line of the file
cut -c -3 file.txt #Print the first 3 characters from each line of the file
head
It is used to read the file from the beginning.

Examples:

head -n 5 file.txt #Print the first 5 lines of the file
head -n -5 file.txt #Print the lines after omitting the last 5 lines
head -c 50 file.txt #Print the first 50 characters of the file
head -q file1.txt file2.txt #Print the content of multiple files
tail
It is used to read the file from the end.

Examples:

tail -n 4 file.txt #Print the last 4 lines of the file
tail -n -7 file.txt #Print the lines after omitting the first 7 lines
tail -c 50 file.txt #Print the last 50 characters of the file
tail -n 5 file1.txt file2.txt #Print the last 5 lines of two files
File Permissions
chmod
It is used to set the permission bits for the files and folders.

Examples:

#Owner can read & write, the group users can read and others can execute
chmod 642 filename
#Owner can read, write and execute, the group users can execute and others can read only
chmod u=rwx,g=x,o=r filename
#Owner can read and write, the group users can write and others can do nothing to the files and folders #of the directory
chmod -R 620 dirname
chown
It is used to change the ownership of a file for the owner or the group users. It requires root privileges to execute.

Examples:

sudo chown -c username filename #Change the ownership of a file
sudo chown :groupname filename #Change the ownership of a group
#Change the ownership by mentioning the usernames
sudo chown --from=fahmida root linuxhint
File Compression and Decompression
gzip
It is used to compress the file by keeping the original file mode, timestamp and ownership.

Examples:

gzip filename #Compress single file
gzip file1 file2 file3 #Compress multiple files
gzip -v filename #Display the percentage of compression
gzip -r directory #Compress all files of a directory
tar
It is used to create compressed achieve files of large files and folders that can be transferred from one location to another.Examples:

tar -cvf filename.tar /home/fahmida/ #Create a compress file of .tar extension
tar -cvzf filename.tgz /home/fahmida/ #Create a compress file of .tgz extension
tar -cvfj filename.bz2 /home/fahmida/ #Create a compress file of .bz2 extension
zip
It is used to compress the file in .zip format that is supported by many operating systems.

Examples:

zip file.zip file.txt #Compress the file with .zip extension
zip -d file.zip file.txt #Remove the file from the zip archive
zip -u file.zip file.txt #Update the file in the zip archive
unzip
It is used to unzip the files and folders from the zip achieve.

Examples:

unzip file.zip #Decompress file in the current location from the zip archive
sudo unzip file.zip -d /temp #Decompress file in the particular folder from the zip archive
Directory operations
pwd
It is used to know the path of the current working directory.

Examples:

pwd #Display the current working directory
pwd –L #Display the logical working directory
pwd –P #Display the physical working directory
mkdir
It is used to create a new directory.

Examples:

mkdir dirname #Create a single directory
mkdir dir1, dir2, dir3 #Create multiple directory
mkdir –m777 dirname #Create a directory with permission
rmdir
It is used to remove any directory.

Examples:

rmdir dirname #Remove single directory
rmdir dir1, dir2, dir3 #Remove multiple directory
#Remove the child directory first and remove the parent directory
rmdir -p parent_dir/child_dir
ls
It is used to print the list of files and folders of the current path or a particular path.

Examples:

ls #Display the files and folders in the default format
ls -a #Display files and folders with hidden files
ls -l #Display the files and folders with the detailed information
ls -h #Display the files and folders in human-readable format
ls -r #Display the files and folders in reverse order
ls -F #Display folders with ‘/’
cd
It is used to change the directory.

Examples:

cd dirname #Change to a directory
cd dir1/dir2 #Change to a directory that is inside another directory
cd / #Change to the root directory
cd #Change to the home directory
Searching Commands
grep
It is used to search the particular string in a file.

Examples:

grep 'test' file.txt #Print the lines that match the word, 'test'
grep -itest’ file.txt #Print the lines that match the word, 'test' case-insensitively
grep ‘^test’ file.txt #Print the lines that match the word, 'test' at the beginning of the line
greptest$’ file.txt #Print the lines that match the word, 'test' at the end of the line
locate
It is used to search a file by name.

Examples:

locate filename #Search a particular file
locate "*.txt" -n 15 #Search text files with the limit
locate -c [.sh]* #Count the number of matches
locate -i filename #Search a file in a case-insensitive manner
find
It is used to search and locate the files and folders based on the condition.

Examples:

find . -name filename.txt #Search a file in the current directory
find . -iname filename.txt #Search a file case-insensitively
find /temp -name filename.txt #Search the file in the particular folder
find / -type d -name dirname #Search the directory in ‘/’ folder
whereis
It is used to search the location of the source, binary, and the manual page files for a command.

Examples:

whereis -l #Find the directories where the `whereis` command will search
whereis bash #Find the location of the `bash`
whereis man uptime #Find the location of `man` and `uptime`
Network Information
ping
It is used to test a host is reachable or not in the network.

Examples:

ping www.google.com #Test using the URL address
ping 142.250.199.36 #Test using IP address
ping -c 5 www.google.com #Test will stop after sending 5 packets
ping -i 3 www.google.com #Test using 3 seconds interval
ifconfig
It is used to configure, manage, and query network interface parameters by using a command-line interface or system configuration script. You have to install the net-tools package to use this command.

Examples:

ifconfig #Display all active interfaces
ifconfig -a #Display all active or inactive interfaces
ifconfig eth0 #Display information about the specific interface
ifconfig eth0 up #Activate the particular interface
ifconfig eth0 down #Deactivate the particular interface
ifconfig eth0 172.16.25.125 #Set the IP address for the particular interface
dig
It is used to search the DNS name servers for DNS lookup.

Examples:

dig example.com #Find the IP address of the hostname
dig 93.184.216.34 #Find the hostname of the IP address
dig example.com MX #Find the MX of a hostname
netstat
It is used to get information about the network activities and display which ports are open or have established connections. It is a useful tool to debug network problems.

Examples:

netstat –a    #Print all ports and connections
netstat –at   #Print all TCP ports
netstat –au  #Print all UDP ports
netstat -l     #Print all listening ports of all protocols
ip
It is used to bring the interface up or down, assign and remove the address, etc.

Examples:

ip addr show  #Display information of all IP addresses
ip addr show dev eth0  #Display information about a single interface
sudo ip address add 192.168.10.50/24 dev eth0 #Assign IP to an interface
Bash Shortcut Keys
alt+ctrl+t
It is used to open a new terminal window.
ctrl+c
It is used to stop the running command.
ctrl+a
It is used to go to the start of the line.
ctrl+e
It is used to go to the end of the line.
ctrl+u
It is used to cut the line before the cursor to the clipboard.
ctrl+k
It is used to cut the line after the cursor to the clipboard.
ctrl+r
It is used to search history.
ctrl+z
It is used to suspend the current foreground process.
!!
It is used to repeat the last command.
!$
It is used to read the last argument of the previous command.
!*
It is used to read all arguments of the previous command.
Bash Script Basics
Variables
The variable is used to store and read data.

Example:

website="linuxhint.com"   #Assign a string value to a variable
echo $website  #Print the value of the variable
echo "The website name is $website"   #Print the variable with another string
Length
The length of a string can be calculated in bash in different ways. The simple way to count the length is shown below.

Example:

var="Hello World"   #Assign String value
echo ${#var}            #Print the length of the sting
Substring
Sometimes it requires cutting the portion of a string that is called substring.

Example:

var="Hello World"   #Assign String value
echo "${var:0:5}"     #Print the substring, ‘Hello’
echo "${var:6:5}"     #Print the substring, ‘World’
Uppercase
The string can be converted into uppercase by using `tr` command and ‘^^’ operator.

Example:

var="Hello"
echo $var | tr [:lower:] [:upper:]  #Convert to uppercase using `tr`
echo ${var^^}     #Convert to uppercase using '^^'
Lowercase
The string can be converted into lowercase by using `tr` command and ‘,,’ operator.

Example:

var="Hello"
echo $var | tr [A-Z] [a-z]  #Convert to lowercase using `tr`
echo ${var,,}     #Convert to lowercase using '^^'
If Statement
If statement is used to define the conditional statements.

Example:

str="file.txt"
if [[ -f $str ]]; then        #Check the file exists or not
  echo "$str is a file."
elif [[ -d $str ]]; then     #Check the directory exist or not
  echo "$str is a directory."
else
  echo "$str is not a fir or directory."
fi
Case statement
The case statement can be used as an alternative to if statement.

Example:

id=45
case $id in
    67) echo "Group-1";;             #Match with an ID
    45 | 89)  echo "Group-2";;         #Match with any of two IDs
    92 | 12 | 54) echo "Group-3" ;;     #Match with any of three IDs
    *)  echo "You are not selected." ;;
esac
For loop
It is used to iterate some statements multiple times or read the array values.

Example:

for i in 23 67 45 11 89         #Iterate the loop for 5 times
do
   echo "The value of i = $i"    #Print each iteration value
done
While loop
It is used as the alternative of for loop.

Example:

n=10     #Initialize a number
while [ $n -le 20 ]     #Iterate the loop until the value reaches to 20
do
  echo "n=$n"       #Print the current value of $n
  n=$(( $n + 5 ))    #Increment the value of $n by 5
done
Function
It is used to define a block of code with a name that can be executed anytime by calling the function name.

Example:

function_name() {      #Define the function
  echo "Hello World"
}
echo $(function_name)   #Call the function
eval
It is used to execute arguments like a shell command.

Example:

c1=$(( 10 + 15 ))    #Define the argument
c2="echo "             #Define the second argument
eval $c1 $c2              #Execute the arguments
set
It is used to control certain flags and features in Bash to set the behavior of the scripts.

Examples:

set –C  #Disable the feature of overwriting the file
set –e  #Stop script immediately when an error occurs
unset
Ii is used to delete the variables during the program execution. It can be used to delete both functions and shell variables.

Example:

var="Hello World"   #Assign String value
echo $var    #Print the assigned variable
unset $var    #Unset the variable
echo $var     #Print the variable after unset

About the author

Linux Wolfman

Linux Wolfman is interested in Operating Systems, File Systems, Databases and Analytics and always watching for new technologies and trends. Reach me by tweeting to @linuxhint and ask for the Wolfman.