Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Linux

The document provides a comprehensive overview of Linux commands, Bash scripting, and the differences between Linux and Unix. It includes command usage, file management, process management, and scripting examples, along with a comparison of Linux's open-source nature versus Unix's proprietary model. Additionally, it outlines common shortcuts and presents an assignment for creating a simple database management script in Bash.

Uploaded by

ASK 011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Linux

The document provides a comprehensive overview of Linux commands, Bash scripting, and the differences between Linux and Unix. It includes command usage, file management, process management, and scripting examples, along with a comparison of Linux's open-source nature versus Unix's proprietary model. Additionally, it outlines common shortcuts and presents an assignment for creating a simple database management script in Bash.

Uploaded by

ASK 011
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Password : admin123

Smtp is releated to mail


whoami
pwd : The pwd command stands for (print working directory).
It displays the current working location or directory of the user.
Absolute path as output
/ : in linux all files are in ‘/’(root directory)
ls : list the files and directories. It will list out all the files in the directed
folder.
ls -l :long list
cd : change directory
mkdir : make directory

cd/home/Aniket/galaxy/earth ->Absolute path


cd galaxy -> Relative path

Linux Bash

The Linux Bash is also known as 'Bourne-again Shell. written by Brian Fox
The Bash is a command language interpreter as well as a programming
language. It supports variables, functions, and flow control, like other
programming languages. It can also read and execute the commands from a file,
which is called a shell script.

What is Shell

The terminal contains the shell; it allows us to execute the commands to interact with
the system. We can perform various operations such as store and retrieve data,
process information, and various other simple as well as complex tasks.

Open terminal CTRL+ALT+T.

Perform some basic operations such as date, cal, ls, and pwd

What is Scripting

Shell Scripts: It is a text file that has shell commands and executes them when it is
used. Bash reads and executes the commands then exits.

Difference between Linux and Unix

Linux Unix
It is an open-source operating system It is an operating system which can be only
which is freely available to everyone. used by its copyrighters.

different distros Ubuntu, Redhat, Fedora, IBM AIX, HP-UX and Sun Solaris.
etc

Nowadays, Linux is in great demand. It was developed mainly for servers,


Anyone can use Linux whether a home workstations and mainframes.
user, developer or a student.

Linux is used everywhere from servers, It is used in servers, workstations and PCs.
PC, smartphones, tablets to mainframes
and supercomputers.

Linux is freely distributed,downloaded, Unix copyright vendors decide different costs


and distributed through magazines also. for their respective Unix Operating systems.
And priced distros of Linux are also
cheaper than Windows.

As it is open source, it is developed by Unix was developed by AT&T Labs, various


sharing and collaboration of codes by commercial vendors and non-profit
world-wide developers. organizations.

Linux kernel is developed by the Unix has three distributions IBM AIX, HP-UX
community of developers from different and Sun Solaris. Apple also uses Unix to
parts of the world. Although the father of make OSX operating system.
Linux, Linus Torvalds oversees things.

Linux is just the kernel. Unix is a complete package of Operating


system.

It provides higher security. Linux has Unix is also highly secured. It has about 85-
about 60-100 viruses listed till date. 120 viruses listed till date

As Linux is open-source,whenever a user In Unix, users have to wait for some time for
post any kind of threat, developers from the problem to be resolved.
all over the world start working on it. And
hence, it provides faster solution.

1) Change from the current directory to a new directory


2) Change directory using an absolute path

To change the directory by using an absolute path, we have to mention the whole
path starting from the root.

From the above output, we are changing our directory to 'certs' from 'cups.' So, we
have provided the whole path "/run/cups/certs" starting from the root (/). This is called
an absolute path.

3) Change directory using a relative path

we have changed our directory from 'cups' to 'certs,' but have not mentioned the
whole path. This is the relative path.

4) Change to the home directory

1. cd ~

"cd ~" command has brought us to our home directory.

5) Change to the root directory

6) Change to another user's home directory

cd ~username
7) Change up to multiple Sub Directories

cd Dir1/Dir2/Dir3....

The ls is the list command in Linux


It will show the full list or content of your directory

ls option Description
ls -a ls -a shows whole list + hidden files.

ls -l long list .

ls -lh file sizes in human readable format. Size of the file is very
difficult to read when displayed in terms of byte. The (ls -
lh)command will give you the data in terms of Mb, Gb, Tb, etc.

ls -lhS If you want to display your files in descending order (highest at


the top) according to their size, then you can use (ls -lhS)
command.

ls -l - -block- It is used to display the files in a specific size format. Here, in


size=[SIZE] [SIZE] you can assign size according to your requirement.

ls -d */ It is used to display only subdirectories.

ls -g or ls -lG With this you can exclude column of group information and
owner.

ls -n It is used to print group ID and owner ID instead of their names.

ls -- This command is used to print list as colored or discolored.


color=[VALUE]

ls -li This command prints the index number if file is in the first
column.

ls -p It is used to identify the directory easily by marking the


directories with a slash (/) line sign.

ls -r It is used to print the list in reverse order.

ls -R It will display the content of the sub-directories also.

ls -lX It will group the files with same extensions together in the list.

ls -lt It will sort the list by displaying recently modified filed at top.

ls ~ It gives the contents of home directory.

ls ../ It give the contents of parent directory.

ls --version It checks the version of ls command.

Rename Folder in Linux


Linux commands List

Commands Description

cal Displays calendar.


cd Changes directory.

chgrp Changes group.

chmod Changes permission for a file or directory.

chown Changes the owner of a file or directory.

chsh Changes the shell.

clear Clears the terminal.

comm Compares two streams or files.

cp Copies file content from one file to another file.

cut Used to display the desired column from a file.

date Displays the current date.

df Checks the disk space in the system.

echo (same as printf)

exit Exits from the current user group to the last group.

file Displays the type of file.

find Finds files for a particular search.

gpasswd Transfers group membership to another user.

grep Filters lines of text containing a certain string.

groupadd Creates a group.

groupdel Permanently removes a group.

groupmod Changes group name.

groups Displays the group name to which the current user belongs to.

gzip / gunzip Compresses a file / Decompress a gzip file.

head Displays the first ten lines of a file.

history Displays older commands from the shell command history.

id Tells about the user's id in the system.

ls Lists all the files of a directory.

man Displays the manual page for the specified command.

mkdir Creates directory.


mv Renames directories or files.

od Displays a file content in octal format.

passwd Set a password for a user group.

pwd Display the current working directory location.

PS1 Change the prompt name in the terminal.

rm Removes a file.

rmdir Removes a directory.

sort sorts the content in alphabetical order.

su It allows a user to run a shell as another user.

sudo It allows a user to start a program with the credentials of another user.

time Displays time taken to execute a command.

touch It creates an empty file.

whoami Tells the name of the user.

>cd . ->represent current path

>cd .. -> represent parent directory

>cd ../../..
rmdir directory
>rmdir pune ->delete single directory
>rm -r galaxy ->delete full directory for galaxy to …..

>touch file name ->to create


file
e.g >touch
>rm Hello.txt
file name to remove any file like .txt, .sh
e.g >rm Hello.txt
1.>echo “Hello world” -> works like printf
o/p>Hello world
2.>echo Hello world
o/p>Hello world
3.>echo Hello.txt
o/p>Hello.txt

>touch file name ->to create file


e.g >touch Hello.txt
>touch Hello{1..10}.txt ->10 files get created
>rm Hello{1..10}.txt ->10 files deleated

Create 10 files of each .txt .ppt .sh

Delete all files

>echo hello.txt > hi


>ls overwrit
hi e

>cat hi
hello.txt

>echo “GB” << gb.txt


>cat gb.txt Appen
GB d
Weather the command is present in your system or not use which
command
>which ls
>which nano
 Create file script file
>nano hello.txt
 Ctrl s ->Save
 Ctrl x -> Exit Shell of
echo “Hello world Good Morning” hello.txt

Ctrl s

Ctrl x

>bash hello.txt
Hello world Good Morning

>nano hello.txt
 -e then use \n
 nusta \n nhi chanlar use both \e and \n
Shell of
echo -e “Hello world \n Good Morning” hello.txt

Ctrl s

Ctrl x

>bash hello.txt
Hello world
Good Morning

$ : (same as printf)
>nano hello.txt
Shell of
a=10
echo a

> bash hello.txt


a
V/S
>nano hello.txt
Shell of
a=10
echo $a

> bash hello.txt


10
Shell Scripting
#!/bin/bash
Read : (same as scanf)
>nano hello.txt

>bash hello.txt
>nano hello.txt

1.Basic Pattern Search:


>grep “apple” fruit.txt
apple

2.Case-Insensitive Search:
>grep -i "MANGO" fruits.txt
mango -i : ignores case

3.Search for Lines Containing "melon":


>grep “melon” fruits.txt
water melon
mustard melon

4.

5.

6,Count Lines Matching a Pattern -c


7.-n : gives line number
8.Invert the Match:
To find lines that do not contain the word "apple" -v

Infinite loop Ctrl+C


Sorting (sort -n file name)
>nano num.sh
for loop
>nano hello.txt

>nano hello.txt
>nano hello.txt
>nano hello.txt

Space ahe itha


nhi dila tar
error yeil

O\P works like switch case

Further 3 types of loop


1 for
2 while-> while condition is true
3 until -> till the time condition is false
 lt -> less than
 gt ->greater than
 eq -> equal to
 ne -> not equal to
 le -> less than or equal to
 ge -> greater than or equal to
Unix/Linux Command Reference
File Commands
1. ls Directory listing
2. ls -al Formatted listing with hidden files
3. ls -lt Sorting the Formatted listing by time modification
4. cd dir Change directory to dir
5. cd Change to home directory
6. pwd Show current working directory
7. mkdir dir Creating a directory dir
8. cat >file Places the standard input into the file
9. more file Output the contents of the file
10. head file Output the first 10 lines of the file
11. tail file Output the last 10 lines of the file
12. tail -f file Output the contents of file as it grows,starting with
the last 10 lines
13. touch file Create or update file
14. rm file Deleting the file
15. rm -r dir Deleting the directory
16. rm -f file Force to remove the file
17. rm -rf dir Force to remove the directory dir
18. cp file1 file2 Copy the contents of file1 to file2
19. cp -r dir1 dir2 Copy dir1 to dir2;create dir2 if not present
20. mv file1 file2 Rename or move file1 to file2,if file2 is an
existing
directory
21. ln -s file link Create symbolic link link to file

Process management
1. ps To display the currently working processes
2. top Display all running process
Unix/Linux Command Reference
3. kill pid Kill the process with given pid
4. killall proc Kill all the process named proc
5. pkill pattern Will kill all processes matching the pattern
6. bg List stopped or background jobs,resume a stopped
job in the background
7. fg Brings the most recent job to foreground
8. fg n Brings job n to the foreground

File permission
1. chmod octal file Change the permission of file to octal,which
can
be found separately for user,group,world by
adding,
• 4-read(r)
• 2-write(w)
• 1-execute(x)
Searching
1. grep pattern file Search for pattern in file
2. grep -r pattern dir Search recursively for pattern in dir
3. command | grep
pattern
Search pattern in the output of a command
4. locate file Find all instances of file
5. find . -name filename Searches in the current directory
(represented by
a period) and below it, for files and directories with
names starting with filename
6. pgrep pattern Searches for all the named processes , that
matches with the pattern and, by default, returns
their ID

System Info
1. date Show the current date and time
2. cal Show this month's calender
3. uptime Show current uptime
4. w Display who is on line
5. whoami Who you are logged in as
Unix/Linux Command Reference
6. finger user Display information about user
7. uname -a Show kernel information
8. cat /proc/cpuinfo Cpu information
9. cat proc/meminfo Memory information
10. man command Show the manual for command
11. df Show the disk usage
12. du Show directory space usage
13. free Show memory and swap usage
14. whereis app Show possible locations of app
15. which app Show which applications will be run by default

Compression
1. tar cf file.tar file Create tar named file.tar containing file
2. tar xf file.tar Extract the files from file.tar
3. tar czf file.tar.gz files Create a tar with Gzip compression
4. tar xzf file.tar.gz Extract a tar using Gzip
5. tar cjf file.tar.bz2 Create tar with Bzip2 compression
6. tar xjf file.tar.bz2 Extract a tar using Bzip2
7. gzip file Compresses file and renames it to file.gz
8. gzip -d file.gz Decompresses file.gz back to file

Network
1. ping host Ping host and output results
2. whois domain Get whois information for domains
3. dig domain Get DNS information for domain
4. dig -x host Reverse lookup host
5. wget file Download file
6. wget -c file Continue a stopped download
Unix/Linux Command Reference

Shortcuts
1. ctrl+c Halts the current command
2. ctrl+z Stops the current command, resume with fg in the
foreground or bg in the background
3. ctrl+d Logout the current session, similar to exit
4. ctrl+w Erases one word in the current line
5. ctrl+u Erases the whole line
6. ctrl+r Type to bring up a recent command
7. !! Repeats the last command
8. exit Logout the current session

Assignments
1).Write a shell script to create a menu driven program for adding,
deletion or finding a record in a database. Database should have the field
like rollno, name, semester and marks of three subjects. Last option of the
menu should be to exit the menu.
#!/bin/bash
# Initialize an associative array to act as a simple database
declare -A database

# Function to add a record


add_record() {
read -p "Enter Roll Number: " rollno
read -p "Enter Name: " name
read -p "Enter Semester: " semester
read -p "Enter Marks for Subject 1: " subject1
read -p "Enter Marks for Subject 2: " subject2
read -p "Enter Marks for Subject 3: " subject3
database["$rollno"]="Roll No: $rollno, Name: $name, Semester:
$semester, Subject1: $subject1, Subject2: $subject2, Subject3:
$subject3"
echo "Record added successfully."
}

# Function to delete a record


delete_record() {
read -p "Enter Roll Number to delete: " rollno
if [[ -n ${database["$rollno"]} ]]; then
unset database["$rollno"]
echo "Record deleted successfully."
else
echo "Record not found."
fi
}

# Function to find a record


find_record() {
read -p "Enter Roll Number to find: " rollno
if [[ -n ${database["$rollno"]} ]]; then
echo "Record found:"
echo "${database["$rollno"]}"
else
echo "Record not found."
fi
}

# Menu
while true; do
echo "Menu:"
echo "1. Add Record"
echo "2. Delete Record"
echo "3. Find Record"
echo "4. Exit"
read -p "Enter your choice: " choice

case $choice in
1)
add_record
;;
2)
delete_record
;;
3)
find_record
;;
4)
echo "Exiting the menu."
exit 0
;;
*)
echo "Invalid choice. Please enter a valid option."
;;
esac
done

2) Write a Linux shell script to accept 10 number and tell how many are
+tive, -tive and zero.
#!/bin/bash

# Initialize variables to count positive, negative, and zero numbers


positive_count=0
negative_count=0
zero_count=0

echo "Enter 10 numbers:"

# Loop to read and classify numbers


for ((i = 1; i <= 10; i++)); do
read -p "Number-$i: " num

if ((num > 0)); then


positive_count=$((positive_count + 1))
elif ((num < 0)); then
negative_count=$((negative_count + 1))
else
zero_count=$((zero_count + 1))
fi
done

# Display the results


echo "Positive numbers: $positive_count"
echo "Negative numbers: $negative_count"
echo "Zeroes: $zero_count"
3) Write a shell script to accept five number and display max and min
value.
#!/bin/bash

# Initialize variables to store maximum and minimum values


max=0
min=0
count=0

echo "Enter 5 numbers:"

# Loop to read and find the maximum and minimum values


for ((i = 1; i <= 5; i++)); do
read -p "Number-$i: " num

# For the first number, initialize max and min


if [ $count -eq 0 ]; then
max=$num
min=$num
count=1
else
if [ $num -gt $max ]; then
max=$num
fi

if [ $num -lt $min ]; then


min=$num
fi
fi
done
# Display the maximum and minimum values
echo "Maximum value: $max"
echo "Minimum value: $min"

1. Shell Script to display the first 10 natural numbers.


Expected Output :
1 2 3 4 5 6 7 8 9 10
#!/bin/bash

# Initialize a variable to store the sum


sum=0

# Loop to calculate the sum of the first 10 natural numbers


for ((i = 1; i <= 10; i++)); do
sum=$((sum + i))
done

# Display the sum


echo "The sum of the first 10 natural numbers is: $sum"
4. Shell Script to read 10 numbers from the keyboard and find their sum
and average.
#!/bin/bash

# Initialize variables for sum and count


sum=0
count=10

echo "Enter 10 numbers:"

# Loop to read and calculate the sum


for ((i = 1; i <= 10; i++)); do
read -p "Number-$i: " num
sum=$((sum + num))
done

# Calculate the average


average=$(bc -l <<< "scale=2; $sum / $count")

# Display the sum and average


echo "The sum of 10 numbers is: $sum"
echo "The average is: $average"
9. Shell Script to display a pattern like a right angle triangle using an
asterisk.

*
**
***
****
#!/bin/bash

read -p "Enter the number of rows: " rows

for ((i = 1; i <= rows; i++)); do


for ((j = 1; j <= i; j++)); do
echo -n "* "
done
echo
done
10. Shell Script to display a pattern like a right angle triangle with a
number.
The pattern like :

1
12
123
1234
11. Shell Script to make such a pattern like a right angle triangle with a
number which will repeat a number in a row.
1
22
333
4444
#!/bin/bash

read -p "Enter the number of rows: " rows

for ((i = 1; i <= rows; i++)); do


for ((j = 1; j <= i; j++)); do
echo -n "$i"
done
echo
done

12. Shell Script to make such a pattern like a right angle triangle with the
number increased by 1.
1
23
456
7 8 9 10

You might also like