0% found this document useful (0 votes)
14 views35 pages

Essential Linux Command Utilities Guide

The document is a comprehensive guide on various command-line utilities for directory handling, file manipulation, string manipulation, process management, network utilities, and general-purpose tasks in an operating system. It includes detailed commands with examples for each utility, along with scripts for specific tasks such as checking file existence, calculating sums, and managing files. Additionally, it provides C code snippets for file operations using system calls.

Uploaded by

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

Essential Linux Command Utilities Guide

The document is a comprehensive guide on various command-line utilities for directory handling, file manipulation, string manipulation, process management, network utilities, and general-purpose tasks in an operating system. It includes detailed commands with examples for each utility, along with scripts for specific tasks such as checking file existence, calculating sums, and managing files. Additionally, it provides C code snippets for file operations using system calls.

Uploaded by

Siraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

OS LAB JOURNAL

CUIN:- 2303140

Directory Handling Utilities

cd
Change the current directory.

● Move to a specific directory:


$ cd foldername
● Move to the parent directory:
$ cd ..
● Move to the home directory:
$ cd ~
● Move using a relative path:
$ cd folder/anotherfolder

mkdir
Create new directories.

● Create a single directory:


$ mkdir new_folder
● Create nested directories:
$ mkdir -p parent/child

rmdir
Remove empty directories.

● Remove a single empty directory:


$ rmdir empty_folder
● Remove nested empty directories:
$ rmdir -p parent/child

pwd
Print the current working directory.

● Show the current directory:


$ pwd

ls
List files in a directory.

● List files:
$ ls
● List all files including hidden ones:
$ ls -a
● List files with details:
$ ls -l

cat
View or concatenate files.

● Display file contents:


$ cat [Link]
● Concatenate multiple files:
$ cat [Link] [Link] > [Link]

File Manipulation Utilities

cp
Copy files and directories.
● Copy a file:
$ cp [Link] [Link]
● Copy directories recursively:
$ cp -r dir1 dir2

mv
Move or rename files.

● Rename a file:
$ mv [Link] [Link]
● Move a file to another directory:
$ mv [Link] /home/user/

rm
Remove files and directories.

● Delete a file:
$ rm [Link]
● Delete a directory and its contents:
$ rm -rf my_folder/

chmod
Change file permissions.

● Give full permissions to owner:


$ chmod u+rwx [Link]
● Set numeric permissions:
$ chmod 755 [Link]

chown
Change file ownership.

● Change owner to root:


$ chown root [Link]
● Change owner and group:
$ chown user:group [Link]

find
Search for files.

● Find a file by name:


$ find /home -name '[Link]'
● Find empty files:
$ find ./abc -empty

head
Display the first few lines of a file.

● Show the first 10 lines:


$ head [Link]
● Show the first 3 lines:
$ head -n 3 [Link]

tail
Display the last few lines of a file.

● Show the last 10 lines:


$ tail [Link]
● Show the last 3 lines:
$ tail -n 3 [Link]

wc
Count words, lines, and characters in a file.

● Show counts:
$ wc [Link]
● Count only lines:
$ wc -l [Link]
touch
Create an empty file.

● Create a new file:


$ touch [Link]
● Create multiple files:
$ touch file1 file2 file3

String Manipulation Utilities

grep
Search for patterns in a file.

● Case-insensitive search:
$ grep -i 'UNIX' [Link]
● Count occurrences:
$ grep -c 'unix' [Link]

egrep
Extended grep for multiple patterns.

● Search for multiple words:


$ egrep 'error|warning' [Link]
● Case-insensitive search:
$ egrep -i 'unix' [Link]

cut
Extract sections of lines.

● Extract first three bytes:


$ cut -b 1-3 [Link]
● Extract the first field from a CSV file:
$ cut -d ',' -f1 [Link]

paste
Merge lines of files.

● Merge two files line by line:


$ paste [Link] [Link]
● Merge with a delimiter:
$ paste -d '|' [Link] [Link]

tr
Translate or delete characters.

● Convert lowercase to uppercase:


$ echo 'hello' | tr 'a-z' 'A-Z'
● Remove digits:
$ echo 'abc123' | tr -d '0-9'

sort
Sort lines in a file.

● Sort alphabetically:
$ sort [Link]
● Sort numerically:
$ sort -n [Link]

rev
Reverse lines character-wise.

● Reverse each line:


$ rev [Link]
awk
Pattern scanning and processing.

● Print first column:


$ awk '{print $1}' [Link]
● Print specific pattern:
$ awk '/error/ {print}' [Link]

sed
Stream editor for modifying files.

● Replace text:
$ sed 's/old/new/' [Link]
● Delete a line:
$ sed '3d' [Link]

Process Utilities

bs
View running processes.

● List all processes:


$ bs -A

pid
Show process ID.

● Display current PID:


$ echo $$
ppid
Show parent process ID.

● Display PPID:
$ echo $PPID

tty
Display terminal type.

● Show terminal:
$ tty

time
Measure execution time.

● Time a command:
$ time ls

kill
Terminate a process.

● Kill a process:
$ kill 1234
● Force kill:
$ kill -9 1234

exit
Exit the terminal.

● Exit session:
$ exit
Network Utilities

ping
Check network connectivity.

● Ping a website:
$ ping [Link]

ifconfig
Show network interface details.

● Display interfaces:
$ ifconfig

netstat
Display network statistics.

● Show all connections:


$ netstat -a

hostname
Show or set the hostname.

● Display hostname:
$ hostname

traceroute
Trace network packet routes.
● Trace route to Google:
$ traceroute [Link]

telnet
Connect to a remote machine.

● Open a telnet session:


$ telnet [Link]

ssh
Secure shell remote login.

● Connect to server:
$ ssh user@[Link]

Mount
What is mount command?

Idk. ¯\_(ツ)_/¯

General Purpose Utilities

date
Display and set date/time.

● Show date/time:
$ date

history
Show command history.
● List history:
$ history

who
Show logged-in users.

● List users:
$ who

whoami
Show current user.

● Display username:
$ whoami

uptime
Show system uptime.

● Show uptime:
$ uptime

finger
Show user information.

● Check user details:


$ finger username

cal
Show a calendar.

● Display calendar:
$ cal
uname
Show system details.

● Display system info:


$ uname -a

tree
Show directory structure.

● Display tree:
$ tree /home

bc
Command-line calculator.

● Run calculator:
$ bc

tar
Archive files.

● Create a tar file:


$ tar -cvf [Link] files/

zip
Compress files.

● Create a zip file:


$ zip [Link] [Link]
To check if a file exists in the current directory
Script:

if [ -f "[Link]" ]; then
echo "File exists"
else
echo "File does not exist"
fi

To calculate the sum of first 10 natural numbers


Script:

echo "Enter a number: "


read n
sum=0
for((i=1;i<=n;i++))
do
sum=$((sum + i))
done
echo "The sum of First "$n " natural numbers is "$sum".
To find and display the largest number among three given numbers
Script:

echo "Enter Num1"


read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3

if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]


then
echo "Greatest number is "$num1
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
then
echo "Greatest number is "$num2
else
echo "Greatest number is "$num3
fi

Accept a filename as an argument and display its content


Script:

read -p "Enter file name: " filename


while read line
do
echo $line
done < $filename
To calculate the factorial of a given number
Script:

echo "Enter a number: "


read num

fact=1

for((i=2;i<=num;i++))
{
fact=$((fact * i))
}

echo $fact

Take two numbers as input from the user and perform basic arithmetic operations
Script:

echo "Enter two numbers : "


read a
read b

echo "Enter choice: "


echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch
case $ch in
1)res=`echo $a + $b | bc`
;;
2)res=`echo $a - $b | bc`
;;
3)res=`echo $a \* $b | bc`
;;
4)res=`echo "scale=2; $a / $b" | bc`
;;
esac
echo "Result : $res"

To count the number of lines in a given text file


Script:

echo "Enter the filename: "


read filename
wc -l $filename

To concatenate two files and save the result in a new file


Script:

file1=[Link]
file2=[Link]
output_file=[Link]

cat $file1 $file2 > $output_file

echo "Files have been concatenated and saved to" $output_file

Check if a user is logged in and display a message accordingly


Script:

set -eu

if [ $# -ne 1 ]; then
echo "Usage: $0 USERNAME"
exit 1
fi

USER=$1

if who | awk '{print $1}' | grep -q "^$USER$";


then
echo "$USER is logged in."
else
echo "$USER is not logged in."
fi

To find and display the smallest and largest element in an array


Script:

arrayName=(1 2 3 4 5 6 7)

max=${arrayName[0]}
min=${arrayName[0]}

for i in "${arrayName[@]}"
do
if [[ "$i" -gt "$max" ]]; then
max="$i"
fi

if [[ "$i" -lt "$min" ]]; then


min="$i"
fi
done

echo "Max is: $max"


echo "Min is: $min"

Search for a specific pattern in a given text file


Script:

read -p "Enter file name..." fname


read -p "Enter the search pattern" pattern

if [ -f "$fname" ]
then
result=$(grep -i "$pattern" "$fname")
echo "$result"
fi
Find and display all the hidden files in a directory
Script:

dir=$(pwd)
echo -d "We will list all the hidden files in the current Directory $dir"
find . -type f -name ".*" -ls

Sort a list of numbers in ascending/descending order


Script:

sort_asc() {
sorted=$(echo "$1" | tr ' ' '\n' | sort -n)
echo "Ascending order: $sorted"
}

sort_desc() {
sorted=$(echo "$1" | tr ' ' '\n' | sort -nr)
echo "Descending order: $sorted"
}

echo "Enter numbers separated by spaces: "


read numbers

sort_asc “$numbers”

sort_desc “$numbers”
Perform basic string manipulation operations
Script:

str1="Welcome"
str2=" to Linux."
str3="$str1$str2"
echo "Concatenated string is $str3"
str4=$( echo $str3 | cut -c 3-5)
echo "Substring value is $str4"
n=${#str3}
echo "Length of the string is : $n

Count the number of files and directories in the current directory


Script:

dir="/path/to/your/directory"

countfiles=$(find "$dir" -type f | wc -l)


countdir=$(find "$dir" -type d | wc -l)
echo "There are $countfiles files and $countdir directories in the $dir directory.

Find and display the process ID of a specific running process


Script:

function Checkpid () {
ps ax | grep firefox
}
Checkpid

To check if an existing file is read-only or write-only


Script:

read -p "Enter file name..." file_name

if [ -f "$file_name" ]; then
if [ -r "$file_name" ] && ! [ -w "$file_name" ]; then
echo "$file_name is read-only"
elif [ -w "$file_name" ] && ! [ -r "$file_name" ]; then
echo "$file_name is write-only"
else
echo "$file_name has both read and write permissions"
fi
else
echo "Error: File '$file_name' does not exist"
fi
To check if a given user exists on the system
Script:

if id "$1" >/dev/null 2>&1; then


echo "User exists"
else
echo "User does not exist"
fi

Generate a random password with certain criteria


Script:

echo "Welcome to simple password generator"


echo "Please enter the length of the password"
read PASS_LENGTH
openssl rand -base64 48 | cut -c1-$PASS_LENGTH

Display the process ID of the process using the most memory


Script:

function checkmemory () {
ps aux --sort=-%mem | head
}
checkmemory
Display information about the operating system
Script:

echo "Operating system information: "


echo " - OS Name: $(uname -s)"
echo " - Kernel Version: $(uname -r)"
echo " - Machine Architecture: $(uname -m)"
echo " - Hostname: $(hostname)"
echo " - Current User: $(whoami)"

Find and delete files older than a specific number of days in a directory
Script:

directory="path/to/your/directory"
days=2

if [ ! -d "$directory" ]; then
echo "Error: '$directory' is not a valid directory."
exit 1
fi

find "$directory" -type f -mtime +$days -exec rm -f {} \;

echo "Files older than $days days in '$directory' have been deleted.

To automate the backup of a specified directory


Script:

backup="/home/ubuntu/playground"
dest="/home/ubuntu/backup_test"

day=$(date +%A)

hostname=$(hostname -s)

archive="$hostname-$[Link]"

tar czf $dest/$archive $backup

echo "Backup finished"

Monitor free disk space and send an alert if it falls below a certain threshold
Script:

threshold=10
free_space=$(df / | awk 'NR==2 {print $5}' | sed 's/%//')

if [ "$free_space" -lt "$threshold" ]; then


echo "Warning: Free disk space is below $threshold%"
fi

- Create a file, allow the user to write data to the file, display the contents and close
the file using system calls.

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

int main() {
char filename[] = "example_file.txt";
int fd;
char data[100];
char buffer[100];
ssize_t bytes_read;

fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);


if (fd == -1) {
perror("Error opening file for writing");
exit(1);
}

printf("Enter data to write to the file: ");


fgets(data, sizeof(data), stdin);

ssize_t bytes_written = write(fd, data, strlen(data));

if (bytes_written == -1) {
perror("Error writing to file");
close(fd);
exit(1);
}

close(fd);

fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("Error opening file for reading");
exit(1);
}

printf("\nFile contents:\n");
while ((bytes_read = read(fd, buffer, sizeof(buffer) - 1)) > 0) {
buffer[bytes_read] = '\0'; // Null-terminate the string
printf("%s", buffer); // Display the contents
}

if (bytes_read == -1) {
perror("Error reading from file");
}

close(fd);

return 0;
}

- Copying a file into another file using system calls.

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 1024

void copy_file(const char *source, const char *destination) {


int src_fd, dest_fd, bytes_read, bytes_written;
char buffer[BUFFER_SIZE];

src_fd = open(source, O_RDONLY);


if (src_fd == -1) {
perror("Error opening source file");
exit(1);
}

dest_fd = open(destination, O_WRONLY | O_CREAT | O_TRUNC, 0644);


if (dest_fd == -1) {
perror("Error opening destination file");
close(src_fd);
exit(1);
}

while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {


bytes_written = write(dest_fd, buffer, bytes_read);

if (bytes_written != bytes_read) {
perror("Error writing to destination file");
close(src_fd);
close(dest_fd);
exit(1);
}
}

if (bytes_read == -1) {
perror("Error reading source file");
}

close(src_fd);
close(dest_fd);

int main(int argc, char *argv[]) {


if (argc != 3) {
fprintf(stderr, "Usage: %s <source_file> <destination_file>\n", argv[0]);
exit(1);
}
copy_file(argv[1], argv[2]);
printf("File copied successfully from %s to %s\n", argv[1], argv[2]);

return 0;
}

- Display the file details including owner, size, access permissions and file access time
using system calls

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <time.h>

void display_file_details (const char *file_path) {


struct stat file_info;

if (stat(file_path, &file_info) == -1) {


perror("Error getting file details");
exit(1);
}

struct passwd *owner = getpwuid(file_info.st_uid);


if (owner == NULL) {
perror("Error retrieving owner information");
exit(1);
}

struct group *grp = getgrgid(file_info.st_gid);


if (grp == NULL) {
perror("Error retrieving group information");
exit(1);
}

printf("Permissions: ");
printf((S_ISDIR(file_info.st_mode)) ? "d" : "-");
printf((file_info.st_mode & S_IRUSR) ? "r" : "-");
printf((file_info.st_mode & S_IWUSR) ? "w" : "-");
printf((file_info.st_mode & S_IXUSR) ? "x" : "-");
printf((file_info.st_mode & S_IRGRP) ? "r" : "-");
printf((file_info.st_mode & S_IWGRP) ? "w" : "-");
printf((file_info.st_mode & S_IXGRP) ? "x" : "-");
printf((file_info.st_mode & S_IROTH) ? "r" : "-");
printf((file_info.st_mode & S_IWOTH) ? "w" : "-");
printf((file_info.st_mode & S_IXOTH) ? "x" : "-");
printf("\n");

printf("Size: %lld bytes\n", (long long)file_info.st_size);

printf("Owner: %s\n", owner->pw_name);


printf("Group: %s\n", grp->gr_name);

char time_str[100];
struct tm *time_info = localtime(&file_info.st_atime);
strftime(time_str, sizeof(time_str), "%Y-%m-%d%H:%M:%S", time_info);
printf("Last accessed: %s\n", time_str);
}

int main(int argc, char *argv[]) {


if (argc != 2) {
fprintf(stderr, "Usage: %s <file_path>\n", argv[0]);
exit(1);
}

display_file_details(argv[1]);

return 0;
}

- Creation of a child process and allow the parent to display “parent” and the child to
display “child” on the screen.

#include <stdio.h>
#include <unistd.h>

int main() {
pid_t pid = fork();

if (pid < 0) {
perror("Error occurred while creating the parent/child process");
return 1;
}

if (pid == 0) {
printf("child\n");
}
else {
printf("parent\n");
}

return 0;
}

- Creation of a child process to perform a task and before terminating, the parent
waits for the child to finish its task.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid = fork();

if (pid < 0) {
perror("Fork failed");
return 1;
}

if (pid == 0) {
printf("Child: Performing task...\n");
sleep(3);
printf("Child: Task completed!\n");
}
else {
printf("Parent: Waiting for child to finish...\n");
wait(NULL);
printf("Parent: Child has finished, now exiting.\n");
}

return 0;
}

- Creation of a Zombie process.

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t pid = fork();

if (pid < 0) {
perror("Fork failed");
return 1;
}

if (pid == 0) {
printf("Child: I am exiting now...\n");
_exit(0);
}
else {
printf("Parent: Sleeping to create a zombie process...\n");
sleep(10);
printf("Parent: I am awake now.\n");
}

return 0;
}

- Creation of an Orphan process.

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();

if (pid < 0) {
perror("Fork failed");
return 1;
}

if (pid == 0) {
printf("Child: I am an orphan now...\n");
sleep(10);
printf("Child: I have finished my work and exiting...\n");
}
else {
printf("Parent: I am finishing my work and exiting...\n");
_exit(0);
}

return 0;
}

- Simulate the commands using system calls: echo, ls, cp, mkdir, rm, cat, chmod, mv,
grep.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <string.h>

void simulate_echo(const char *message) {


printf("%s\n", message);
}

void simulate_ls(const char *path) {


DIR *dir = opendir(path);

if (dir == NULL) {
perror("opendir");
return;
}

struct dirent *entry;


while ((entry = readdir(dir)) != NULL) {
printf("%s\n", entry->d_name);
}
closedir(dir);
}

void simulate_mkdir(const char *path) {


if (mkdir(path, 0755) == -1) {
perror("mkdir");
}
}

void simulate_rm(const char *path) {


if (unlink(path) == -1) {
perror("unlink");
}
}

void simulate_chmod(const char *path, mode_t mode) {


if (chmod(path, mode) == -1) {
perror("chmod");
}
}

void simulate_mv(const char *src, const char *dest) {


if (rename(src, dest) == -1) {
perror("rename");
}
}

int main() {
simulate_echo("Hello, world!");

simulate_ls(".");

simulate_mkdir("testdir");

simulate_chmod("[Link]", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

simulate_mv("[Link]", "[Link]");

simulate_rm("[Link]");

return 0;
}

You might also like