0% found this document useful (0 votes)
9 views17 pages

Manual Linux Commands

The document provides a comprehensive list of commands for navigating files and folders, managing users and groups, handling processes, and working with text in a Unix-like operating system. Each command is accompanied by a description, parameters, and examples for clarity. Additionally, it includes pipeline examples and memory management commands to enhance user understanding and application.

Uploaded by

thuynhung0105gl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views17 pages

Manual Linux Commands

The document provides a comprehensive list of commands for navigating files and folders, managing users and groups, handling processes, and working with text in a Unix-like operating system. Each command is accompanied by a description, parameters, and examples for clarity. Additionally, it includes pipeline examples and memory management commands to enhance user understanding and application.

Uploaded by

thuynhung0105gl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

FILES AND FOLDER NAVIGATING (14 commands)

Comma
Description Parameters Example
nd

-l : Displays the files and directories in long


format, which includes more details like size, ls -l
ls Lists the contents of a directory. permissions, owner, and modification time.
ls -a
-a : Shows hidden files (which start with a dot)
along with non-hidden files.

.. : Moves up one directory level cd ..


cd Changes the current directory.
~/ : Moves to the home directory. cd ~/

Prints the current working


pwd
directory.

-p : Creates intermediate directories if they


mkdir Creates a new directory. mkdir -p path/to/new/directory
don't exist.

rmdir Removes an empty directory. Rmdir directory_name

-r : Copies a directory and its contents


cp -r source_directory
recursively.
cp Copies a file or directory. destination_directory
-v : Verbose mode, which displays the name
cp -v file.txt /path/to/new/location/
of each file as it is copied.

-i : Interactive mode, which prompts before


overwriting an existing file. mv -i oldname.txt newname.txt
Moves or renames a file or
mv -u : Updates the destination file only if it is
directory. mv -u file.txt /path/to/new/location/
older than the source file or if it does not
exist.

-r : Removes a directory and its contents


recursively. rm -r directory
rm Removes a file or directory.
-i : Interactive mode, which prompts before rm -i file.txt
deleting each file.
Comma
Description Parameters Example
nd

touch Creates an empty file. touch newfile.txt

less : Pipes output through the less`


cat Displays the contents of a file. ` command, allowing you to scroll through
long files.

Shows the first few lines of a


head -n N : Displays the first N lines of the file. head -n 5 file.txt
file.

Shows the last few lines of a


tail -n N : Displays the last N lines of the file. tail -n 5 file.txt
file.

/pattern : Searches for a pattern in the file.


Displays a file one page at a q : Quits less .
less time, allowing you to navigate less file.txt /search_pattern
SPACEBAR : Scrolls down one page at a time.
through it.
b : Scrolls up one page at a time.

CTRL+O : Saves the file.


CTRL+X : Exits nano .
nano Opens a simple text editor.
CTRL+K : Cuts the current line.
CTRL+U : Pastes the cut line.
USER, GROUP, PERMISSION (16 commands)

Command Description Parameters Example

id
Displays the current user ID (UID) and -u: Shows only the UID.
id -u
id group ID (GID), as well as the -g: Shows only the GID.
id -g
supplementary group IDs. -n: Shows the names instead of the numerical IDs.
id -n

whoami Displays the current username. whoami

-: Switches to the target user's login shell.


-c: Executes a command as the target user without switching to su - alice
su Switches to another user account.
their shell. su -c "ls" bob
-s: Overrides the target user's shell with the specified shell.

Displays a list of currently


logged-in users, along with
w w
information about their current
activities on the system.

Displays a list of recently


logged-in users, along with the
last last
time and duration of their login
sessions.

Displays a list of currently


logged-in users, along with the
who who
terminal they are using and the
time they logged in.
Command Description Parameters Example

Executes a command with elevated


sudo Sudo su
privileges.

adduser Creates a new user account. adduser alice

-a: Adds a supplementary group to the user account. usermod -a -G developers alice
-G: Changes the primary group of the user account. usermod -G staff alice
usermod Modifies an existing user account.
-l: Renames the user account. usermod -l alice_newname alice
-d: Changes the home directory of the user account. usermod -d /home/alice_newdir alice

-remove-home: Removes the user's home directory and mail deluser alice
deluser Deletes a user account.
spool. deluser alice -remove-home

addgroup Creates a new group. addgroup developers

-n: Renames the group. groupmod -n new_developers developers


groupmod Modifies an existing group.
-g: Changes the numerical ID of the group. groupmod -g 1001 developers

delgroup Deletes a group. delgroup developers

user: Specifies the new owner username.


Changes the owner of a file or chown user file.txt
chown -R: Changes ownership recursively, which includes all files and
directory. chown -R user directory/
subdirectories.

group: Specifies the new group name.


Changes the group ownership of a file chgrp group file.txt
chgrp -R: Changes group ownership recursively, which includes all
or directory. chgrp -R group directory/
files and subdirectories.

chmod Changes the permissions of a file or mode: Specifies the permission mode using octal notation. chmod 755 file.txt
directory. u: Changes the permission for the owner. chmod u+x file.txt
g: Changes the permission for the group. chmod o-r fi
o: Changes the permission for others.
a: Changes the permission for all (equivalent to ugo).
Command Description Parameters Example

+: Adds permission.
-: Removes permission.
=: Sets exact permission.

MANAGING PROCESSES AND READ SYSTEM INFORMATION (14 commands)

Command Description Parameters Example

Displays real-time information about


top system processes and resource top
utilization.

-e: Shows information about all processes. ps -e


Shows information about active
ps -f: Displays the full format listing. ps -ef
processes running on the system.
-u: Shows information for a specific user. ps -u alice

-9: Sends a SIGKILL signal to force the process to terminate


Sends a signal to a process to immediately. kill -9 PID
kill
terminate it. -15: Sends a SIGTERM signal to gracefully terminate the kill -15 PID
process.
Command Description Parameters Example

-9: Sends a SIGKILL signal to force the processes to terminate


Sends a signal to all processes with a immediately. killall -9 process_name
killall
certain name to terminate them. -15: Sends a SIGTERM signal to gracefully terminate the killall -15 process_name
processes.

Runs a process at a different priority value: Sets the new priority value. nice -n 10 command
nice
level. -n: Renices an already running process. renice -n 5 -p PID

An interactive text-mode process


htop viewer that provides additional htop
features compared to top.

Displays system memory usage and free


free -h: Shows output in human-readable format.
available memory. free -h

Displays the amount of disk space


df
df available and used on mounted file -h: Shows output in human-readable format.
df -h
systems.

du
Displays disk usage statistics for files -h: Shows output in human-readable format.
du du -h
and directories. -s: Displays only a summary for the specified directory.
du -sh /home/user

Shows how long the system has been


uptime uptime
running and the current load average.

Displays real-time information about


top system processes and resource top
utilization.

ps Shows information about active -e: Shows information about all processes. ps -e
processes running on the system. -f: Displays the full format listing. ps -ef
Command Description Parameters Example

-u: Shows information for a specific user. ps -u alice

-9: Sends a SIGKILL signal to force the process to terminate


Sends a signal to a process to immediately. kill -9 PID
kill
terminate it. -15: Sends a SIGTERM signal to gracefully terminate the kill -15 PID
process.

-9: Sends a SIGKILL signal to force the processes to terminate


Sends a signal to all processes with a immediately. killall -9 process_name
killall
certain name to terminate them. -15: Sends a SIGTERM signal to gracefully terminate the killall -15 process_name
processes.

WORKING WITH THE TEXT (7 commands)


Command Description Parameters Example

-name: Searches for files with a specific name.


find /home -name "*.txt"
Searches for files and directories with -type: Searches for files of a specific type.
find /usr/bin -type f -name "gcc*"
find specific attributes, such as name, size, -size: Searches for files of a specific size.
find /var/log -type f -size +10M
and modification time. -mtime: Searches for files that were modified within a specific
find /home/user -type f -mtime -7
time period.

grep "error" logfile.txt


-i: Makes the search case-insensitive.
Searches for text patterns in files or grep -i "error" logfile.txt
grep -v: Shows lines that do not match the pattern.
output from other commands. grep -v "success" logfile.txt
-c: Displays only the count of matching lines.
grep -c "pattern" file.txt

Counts the number of lines, words, and -l: Displays only the line count.
wc myfile.txt
wc characters in files or input from other -w: Displays only the word count.
wc -l file.txt
commands. -c: Displays only the character count.

Extracts specific columns from files or -f: Specifies the field(s) to extract.
cut cut -f1 -d":" /etc/passwd
input from other commands. -d: Specifies the delimiter character.

-r: Sorts in reverse order. sort myfile.txtsort -r myfile.txt


Sorts lines of text alphabetically or
sort -n: Sorts numerically. sort -n numbers.txt
numerically.
-u: Only displays unique lines. sort -u myfile.txt

Filters out adjacent duplicate lines of


uniq -c: Precedes each line with the number of times it occurs. `sort myfile.txt
text.

{print $1}: Displays only the first column.{sum += $2} END {print awk '{print $1}' file.txt
Searches and manipulates text files
awk sum}: Calculates the sum of the second column./pattern/ {print awk '{sum += $2} END {print sum}' data.txt
according to patterns and actions.
$0}: Searches for a pattern and displays the entire line. awk '/error/ {print $0}' logfile.txt
PIPELINE EXAMPLES
1. Lists all files and directories (including hidden ones) in the current directory and filters out any lines that do not contain "file.txt".
ls -la | grep "file.txt"

2. Displays the contents of `file.txt` and sorts the lines in reverse alphabetical order.
cat file.txt | sort -r

3. Searches for all files modified within the last 7 days in the `/home/user` directory and its subdirectories, and filters the results to only show files containing "log".
find /home/user -type f -mtime -7 | grep "log"

4. Displays a list of running processes, filters out those that do not contain "chrome", and extracts the second column (process ID).
ps aux | grep "chrome" | awk '{print $2}'

5. Displays the most recent entries in the system log file and filters out any lines that do not contain "error".
tail -f /var/log/syslog | grep "error"

6. Displays the last 10 commands executed in the terminal history and removes the timestamp and leading spaces.
history | tail -n 10 | cut -d " " -f 4-

7. Converts the text "hello world" to uppercase.


echo "hello world" | tr '[:lower:]' '[:upper:]'

8. Lists the names of the first 5 files in the current directory.


ls -l | awk '{print $9}' | head -n 5

9. Searches for the word "keyword" in all `.txt` files in the `/home/user` directory and its subdirectories.
find /home/user -type f -name "*.txt" | xargs grep "keyword"
10. Listens on port 1234 for incoming network connections, saves any received data to a file `received.txt`, and filters out any lines that do not contain "pattern".
nc -l -p 1234 | tee received.txt | grep "pattern"

11. Lists files in the current directory (human-readable format) sorted by size (largest first) and displays only the 10 largest files.
ls -lh | sort -k 5nr | head -n 10

12. Downloads the HTML content of a website, filters out the `<title>` tag, and removes any remaining HTML tags using the `sed` command.
curl https://example.com | grep "<title>" | sed 's/<[^>]*>//g'

13. Counts the frequency of commands executed in the terminal history, sorts them by frequency, and displays the top 10 most commonly used commands.
history | awk '{print $2}' | sort | uniq -c | sort -nr | head -n 10

14. Displays the most recent entries in the system log file that contain the word "error" and extracts the message from the sixth column.
tail -f /var/log/syslog | awk '/error/ {print substr($0, index($0,$6))}'

15. Concatenates the contents of two files, searches for the word "keyword" (case-insensitive), and counts the number of lines that match the search pattern.
cat file1.txt file2.txt | grep -i "keyword" | wc -l

16. Lists running processes sorted by CPU usage (lowest first) and displays only the 10 with the lowest usage.
ps aux | sort -nk 3 | tail -n 10

17. Reverses the text "hello world".


echo "hello world" | rev

18. Finds all `.txt` files in the current directory and its subdirectories, and moves them to a directory named `backup`.
find . -type f -name "*.txt" -exec mv {} backup \;

19. Calculates the sum of the second column (separated by commas) in a CSV file.
cat file.txt | awk -F "," '{sum += $2} END {print sum}'
20. Gets the hostname of the current machine, pings it once, and displays the results in the terminal.
uname -a | cut -d " " -f 2 | xargs ping -c 1
MEMORY MANAGEMENT
6. swapoff command:

1. free command: $ sudo swapoff /dev/sda5 && sudo swapon /dev/sdb1


The above command combines swapoff and swapon to deactivate one
$ free -h | grep "Mem" | awk '{print "Total memory: " $2 ", used swap partition (/dev/sda5) and activate another (/dev/sdb1).
memory: " $3}'
The above command uses grep and awk to filter and display the total 7. sync command:
and used memory on your system.
$ sync && echo 3 > /proc/sys/vm/drop_caches
2. top command: $ sync; echo 1 > /proc/sys/vm/drop_caches; echo 2 >
/proc/sys/vm/drop_caches; echo 3 > /proc/sys/vm/drop_caches
$ top -b -n 1 | head -n 20 The first command uses sync to flush all cached data to disk, followed
$ top -b -n 1 | grep -A 10 PID by dropping the page caches, dentries, and inodes in memory. The
The first command uses grep with top to display the top 20 processes second command drops the different types of caches in a single line
sorted by memory usage in non-interactive mode. The second using semicolons.
command uses grep with top to display the top 10 processes sorted by
their process ID (PID).
8. sysctl command:
3. ps command:
$ sudo sysctl -p | grep swappiness
$ ps u | grep firefox $ sysctl vm.overcommit_memory=2 | grep overcommit_memory
The above command uses grep to filter out all Firefox-related processes The first command uses grep to display the current value of the
from the output of ps. swappiness parameter from the output of sysctl. The second command
changes the overcommit_memory parameter to 2 without having to
4. vmstat command: manually edit the configuration file.
$ vmstat 1 10 | grep -v procs
9. psmem command:
The above command uses grep to exclude the procs line from the
output of vmstat, displaying virtual memory stats every second for a $ psmem | grep firefox
total of 10 seconds. The above command uses grep to filter out Firefox-related processes
from the output of psmem, which shows detailed information about
5. swapon command: process memory usage.
$ sudo swapon -s | grep partition
10. atop command:
The above command uses grep to display information about only the
swap partitions that are currently activated. $ atop -m | grep java
The above command uses grep to filter out Java-related processes from $ ps aux | grep firefox | awk '{print $2}' | xargs kill -9
the output of atop, which provides detailed system resource usage The above command uses grep, awk, and xargs to filter, extract the
information. process IDs of Firefox-related processes, and then forcibly terminate
them using kill.

11. lsof command: 16. uptime command:


$ sudo lsof -p $(pidof firefox) | grep -i deleted $ uptime | grep -ohe 'up .*' | sed 's/,//g'
The above command uses grep to display the deleted files by Firefox- The above command uses grep and sed to extract and display the
related processes from the output of lsof, which shows open files system uptime from the output of uptime.
related to a process ID.
17. top command (in batch mode):
12. smem command:
$ top -b -n 1 | grep -E 'Mem|Swap'
$ smem -tw | grep -E "Used|firefox" The above command uses grep to filter out the lines containing
information about the memory and swap usage of the system from the
The above command uses grep to filter out used memory and Firefox- output of top.
related processes from the output of smem, which reports detailed
memory usage statistics for Linux processes. 18. journalctl command:
$ journalctl _TRANSPORT=kernel | grep -i error
13. sar command: The above command uses grep to filter out kernel log entries that
contain the word "error" from the output of journalctl, which queries
$ sar -r 1 5 | grep -v Average and displays the contents of the systemd journal.
The above command uses grep to exclude the Average line from the
output of sar, which provides system activity reports including memory 19. killall command:
and swap space usage.
$ killall -r 'myapp.*' && myapp
14. pmap command: The above command kills all instances of the app whose name starts
with "myapp" and then restarts it.
$ pmap -x $(pidof chrome) | grep shared
The above command uses grep to display the amount of shared 20. htop command:
memory used by Chrome-related processes from the output of pmap,
which shows memory map of a process. $ htop -s PERCENT_CPU | grep chrome
The above command uses grep to filter Chrome-related processes from
15. kill command: the output of htop, which is an interactive process viewer and system
monitor. It sorts the processes by CPU usage percentage.
CREATING A CRONJOB

1. Running a script every day at 6:00am:


12. Running a script every 5 minutes from 8:00am to 5:00pm, Monday
0 6 * * * /path/to/script.sh
through Friday:
2. Running a backup script every Sunday at 11:00pm:
*/5 8-17 * * 1-5 /path/to/script.sh
0 23 * * sun /path/to/backup.sh
13. Running a script every 10 minutes on Sundays:
3. Running a cleanup script every Monday at 3:30am:
*/10 * * * sun /path/to/script.sh
30 3 * * mon /path/to/cleanup.sh
14. Running a script at 6:00am and 6:00pm every day:
4. Running a database backup every Friday at 10:00pm:
0 6,18 * * * /path/to/script.sh
0 22 * * fri /path/to/db-backup.sh
15. Running a script every Friday and Saturday night at 11:30pm:
5. Running a script every hour on the half-hour:
30 23 * * fri,sat /path/to/script.sh
30 * * * * /path/to/script.sh
16. Running a script every 4 hours from 9:00am to 5:00pm, Monday
6. Running a script every 15 minutes: through Friday:
*/15 * * * * /path/to/script.sh 0 */4 9-17 * * 1-5 /path/to/script.sh
7. Running a script at 2:30am every day: 17. Running a script every other day at 3:00am:
30 2 * * * /path/to/script.sh 0 3 */2 * * /path/to/script.sh
8. Running a script every weekday at 9:00am: 18. Running a script every 10 minutes during business hours (8:00am to
0 9 * * 1-5 /path/to/script.sh 5:00pm), Monday through Friday:
9. Running a script every first day of the month at midnight: */10 8-17 * * 1-5 /path/to/script.sh
0 0 1 * * /path/to/script.sh 19. Running a script every 30 minutes on the first 10 days of each month:
10. Running a script every Sunday at midnight: */30 * 1-10 * * /path/to/script.sh
0 0 * * sun /path/to/script.sh 20. Running a script every hour from 7:00am to 7:00pm, Monday through
Friday:
11. Running a script every 30 minutes:
0 7-19 * * 1-5 /path/to/script.sh
*/30 * * * * /path/to/script.sh
1. Create a folder: This script uses the mkdir command to create a new folder/directory.

#!/bin/bash
echo "Enter folder name:"
read folder_name
mkdir $folder_name
echo "Folder created successfully"

2. Delete a file: This script uses the rm command to delete a file.


#!/bin/bash
echo "Enter file name:"
read file_name
rm $file_name
echo "File deleted successfully"

3. Copy a file: This script uses the cp command to copy a file.


#!/bin/bash
echo "Enter source file name:"
read source_file
echo "Enter destination file name:"
read destination_file
cp $source_file $destination_file
echo "File copied successfully"

4. Move a file: This script uses the mv command to move a file.


#!/bin/bash
echo "Enter source file name:"
read source_file
echo "Enter destination file name:"
read destination_file
mv $source_file $destination_file
echo "File moved successfully"
5. List directory contents: This script uses the ls command to list the contents of a directory.

#!/bin/bash
echo "Enter directory name:"
read dir_name
ls $dir_name

6. Change permissions for a file: This script uses the chmod command to change the permissions for a file.
#!/bin/bash
echo "Enter file name:"
read file_name
echo "Enter permission (e.g. 755):"
read permission
chmod $permission $file_name
echo "File permissions changed successfully"

7. Add a user: This script uses the useradd command to add a new user.
#!/bin/bash
echo "Enter username:"
read username
useradd $username
echo "User added successfully"

8. Change password for a user: This script uses the passwd command to change the password for a user.

#!/bin/bash
echo "Enter username:"
read username
passwd $username
echo "Password changed successfully"

9. Create a group: This script uses the groupadd command to create a new group.
#!/bin/bash
echo "Enter group name:"
read group_name
groupadd $group_name
echo "Group created successfully"

10. Check memory usage: This script uses the free command to check the memory usage.
#!/bin/bash
free -m

You might also like