0% found this document useful (0 votes)
2 views

LinuxShellTutorial

The document is a comprehensive Linux Shell tutorial covering various types of shells, important shell commands, file operations, and scripting examples. It includes detailed explanations of commands for file management, process management, text processing, and networking, along with practical examples. Additionally, it outlines course instructions for using Linux in a lab environment, emphasizing the importance of original work and mental health.

Uploaded by

Ral Ralte
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)
2 views

LinuxShellTutorial

The document is a comprehensive Linux Shell tutorial covering various types of shells, important shell commands, file operations, and scripting examples. It includes detailed explanations of commands for file management, process management, text processing, and networking, along with practical examples. Additionally, it outlines course instructions for using Linux in a lab environment, emphasizing the importance of original work and mental health.

Uploaded by

Ral Ralte
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
You are on page 1/ 18

Linux Shell Tutorial

Subhrendu Chattopadhyay
subhrendu@idrbt.ac.in
https://subhrendu1987.github.io/course/AOS/
Types of Shell
System call
• Bourne Shell (sh)
• C Shell (csh)
• TENEX C Shell (tcsh)
• KornShell (ksh)
• Debian Almquist Shell (dash)
• Bourne-again SHell
Device Driver API

2
List of Important Shell Commands
• File Operations • File Viewing
a. ls: List contents of a directory. a. cat: Display the contents of a file.
b. pwd: Print the current directory. b. less: View file contents with scrolling capability.
c. cd: Change directory. c. head: Display the first part of a file.
d. cp: Copy files or directories. d. tail: Display the last part of a file.
e. mv: Move or rename files or directories. e. grep: Search within a file.
f. rm: Remove files or directories. • File Permissions & Ownership
g. touch: Create an empty file. a. chmod: Change file permissions.
h. find: Search for files or directories. b. chown: Change file owner.
• Information Commands c. chgrp: Change group ownership.
a. man: Display the manual page for a command. • Pipe, Redirection, Interprocess Communication
b. info: Display info pages.
c. whatis: Display one-line descriptions.

3
1. File Operations : Example
$ ls
$ pwd
$ mkdir
$ cd
$ cp
$ mv
$ rm
$ touch
$ find

4
2. Information Commands : Example
$ man ls $ info ls
LS(1) User Commands LS(1) 10.1 ‘ls’: List directory contents
NAME ==================================
ls - list directory contents
SYNOPSIS The ‘ls’ program lists information about files (of any type, including
ls [OPTION]... [FILE]... directories). Options and file arguments can be intermixed arbitrarily,
DESCRIPTION as usual.
List information about the FILEs (the current directory by default). …
Sort entries alphabetically if none of
-cftuvSUX nor --sort is specified. $ whatis ls
Mandatory arguments to long options are mandatory for short options ls (1) - list directory contents
too.
-a, --all
do not ignore entries starting with .

5
3.1 File Viewing : Example
$ cat <filename>
$ less <filename>
3.2 Redirection: Example
$ head <filename> $ cat /var/log/auth.log > selected.txt
$ tail <filename> $ cat /var/log/auth.log.1 >> selected.txt
$ grep <filename> $ ls /abc > text.txt; cat text.txt
$ ls /abc 2> text.txt; cat text.txt
$ <CMD> &> output_and_error.log
$ (ls /; ls /abc) > all.log 2>&1 ; cat all.log

stdout (Standard Output):This is the default output stream where a program writes its output
data. It's represented as 1 (though you usually don't need to explicitly specify it).
stderr (Standard Error):This is where a program writes its error messages. It's represented as 2.

6
3.1 File Viewing : Example
$ cat <filename>
$ less <filename>
3.2 Redirection: Example
$ head <filename> $ cat /var/log/auth.log > selected.txt
$ tail <filename> …
$ grep <filename>

3.3 Pipe: Example


$ echo "Hello, World!" | grep "World" # Un-named pipe
$ mkfifo my_pipe # Named pipe
$ echo "Hello, World!" > my_pipe &
$ cat < my_pipe
7
4.1 Compilation: Example
$ mkdir sample; cd sample $ nano main.c
#include <stdio.h>
#include "util.h"

$ nano util.h $ nano util.c int main() {


#ifndef UTIL_H #include "util.h"
int x = 5, y = 3;
#define UTIL_H
int sum, diff;
int add(int a, int b) {
sum = add(x, y);
/* Function to add two integers */ return a + b;
diff = subtract(x, y);
int add(int a, int b); }
printf("Sum: %d\n", sum);
printf("Difference: %d\n", diff);
/* Function to subtract two integers */ int subtract(int a, int b) {
return 0;
int subtract(int a, int b); return a - b;
}
}
#endif // UTIL_H

$ gcc main.c util.c -o my_program

8
4.2 Compilation with Make : Example
$ nano Makefile Variables: Variables are defined using the =
symbol. Once defined, you can use them in
# This is a comment your rules by wrapping their names in $().
# Variables
CXX = gcc # GCC compiler
CXXFLAGS = -Wall -g # C++ flags Targets: Targets define how to produce one
# Targets or more output files from a set of input files.
all: my_program In the example, all is a target that depends
my_program: main.o util.o on my_program. my_program is a target
$(CXX) $(CXXFLAGS) -o my_program main.o util.o that depends on main.o and util.o.
main.o: main.c util.h
$(CXX) $(CXXFLAGS) -c main.c
utility.o: util.c util.h
Commands: Commands are specified after
$(CXX) $(CXXFLAGS) -c util.c
the dependencies for a target. They must be
indented by a tab, not spaces.
clean:
rm -f *.o my_program
Clean: The clean target is a conventional
target in makefiles, which is used to clean up
any files that can be regenerated 9
5. File Permissions & Ownership : Example
$ ls -al <file/folder name>
-rwxrwxr-x <Hardlinks> <Owner> <Group> <Size> <Mod Time> <file/dir name>

● The 1st character indicates the type of file: -: Regular file; d: Directory; l: Symbolic link
● Next 9 characters represent permissions
Octal representation
“rwx” → Read, Write, Execute
● rwx → 111 → octal 7
Partitioned into 3 sections ● rw- → 110 → octal 6
● Owner permission : “rwx------” ● r-x → 101 → octal 5
● Group permission : “---rwx---” ● r-- → 100 → octal 4 …
● Others permission : “------rwx”
File permission
● rwxr-xr-x -> 111 101 101 -> octal 755
● rw-r--r-- -> 110 100 100 -> octal 644
● rwx------ -> 111 000 000 -> octal 700

$ chmod <Mode> <file/dir name>


$ chown <owner>:<group> <filename>
$ chgrp <group> <filename> 10
Diff and Patch: Example
$ diff main.c main_v2.c
8c8
$ diff -u main.c main_v2.c > diff.patch < diff = subtract(x, y);
$ patch main.c < diff.patch # Apply ---
> //diff = subtract(x, y);
$ patch -R main.c < diff.patch # Revert
$ diff -u main.c main_v2.c
--- main.c 2023-08-29 09:34:50.651132095 +0530
+++ main_v2.c 2023-08-30 07:49:45.264289946 +0530
@@ -5,7 +5,7 @@
int x = 5, y = 3;
int sum, diff;
sum = add(x, y);
- diff = subtract(x, y);
+ //diff = subtract(x, y);
printf("Sum: %d\n", sum);
printf("Difference: %d\n", diff);
return 0; 11
Find & Grep: Example
#Find all .txt files in the current directory and its subdirectories

$ find . -name "*.txt"


Find all directories named data in the current directory and its
subdirectories #Display the line numbers of the matches using the -n option

$ find . -type d -name "data" $ grep -n "<Search String>" <filename>


Find all regular files larger than 100 MB in the /home/user directory Use the -v option to display lines that do NOT match the pattern

$ find /home/user -type f -size +100M $ grep -v "<Search String>" <filename>


Find all empty directories

$ find . -type d -empty


$ grep "<Search String>" <filename>
Case insensitive search

$ grep -i "<Search String>" <filename>

12
Shell Script: Example
$nano greet.sh
#!/bin/bash
# This is a comment: Script to greet the user
# Ask the user for their name

read -p "What's your name? " user_name


# Print a personalized greeting

echo "Hello, $user_name!"


# Print the current date and time

echo "Current date and time: $(date)"


# End of script

$ chmod +x greet.sh
$ ./greet.sh # or bash greet.sh

13
Shell Script: Example
$nano loopExample.sh
#!/bin/bash
#Basic numeric range:

echo -e "\033[33;44m Basic numeric range: \033[0m"


for i in {1..5}
do
echo $i
done

14
Shell Script: Example
$nano loopExample.sh
#!/bin/bash

########################################
#Using a variable for the range:

echo -e "\033[33;44m Using a variable for the range: \033[0m"


end=5
for i in $(seq 1 $end)
do
echo $i
done

# Try other examples from the git repo

https://github.com/subhrendu1987/AOS/blob/main/ShellTutorial/loopExample.sh 15
Shell Script: Example
$nano loopExample.sh
#!/bin/bash

########################################
#Looping over an array:

echo -e "\033[33;44m Looping over an array: \033[0m"


fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"
do
echo $fruit
done

16
List of Important Shell Commands
• Text Processing • Process Management
a. wc: Count words, lines, and characters. a. ps: Display active processes.
b. top: Display system processes in real-time.
b. awk: Text processing tool.
c. kill: Terminate processes.
c. sed: Stream editor for text manipulation. d. bg: Run processes in the background.
d. sort: Sort lines in text files. e. fg: Bring a background process to the foreground.
e. cut: Remove sections from lines of files. • System Information
• Networking a. uname: Display system information.
a. ping: Check connectivity to a host. b. hostname: Show or set the system's host name.
b. netstat: Network statistics. c. free: Display memory usage.
c. ifconfig or ip: Display or configure network
interfaces. d. uptime: Show system uptime and load.
d. ssh: Secure shell for remote login. • Environment & Variables
e. scp: Secure copy files between hosts. a. env: Display environment variables.
• Disk Usage b. export: Set environment variables.
a. df: Disk space usage of file systems. c. set: Display or set shell options.
b. du: Estimate file and directory space usage. d. echo: Display a message or variable value.
• Archiving and Compression • Shell Scripting
a. tar: Create or extract tar archives. a. #!: Shebang to indicate script interpreter.
b. gzip: Compress files. b. $?: Exit status of the last executed command.
c. gunzip: Decompress files. c. $#: Number of arguments passed to the script.
d. zip: Create zip archives. d. $*: All arguments passed to the script.
e. unzip: Extract files from zip archives. e. $$: Process ID of the script.

17
Course Instructions
• Environment:
– Use of Linux is necessary for this lab. Use “Oracle Virtualbox” to deploy Linux on top of it using the given OVA file. Although any flavor of
Linux is acceptable, for simplicity we will use Ubuntu 20.04 LTS
i. https://old-releases.ubuntu.com/releases/20.04/
ii. https://cloud-images.ubuntu.com/focal/current/
– Please install Linux before next class.
• We will use google classroom for course management
– Assignment submission, tutorial slides, reference materials and notices will be posted in the LMS
• The course would be implementation intensive. Be ready to learn new things.
• Take care of your mental and physical health. If required communicate with the instructor by anonymous channels.
• At the time of assignment submission:
– Create a base folder named with your roll number only.
– If there are multiple parts in the assignments
i. Create folders inside the base folder with the question number
ii. Place only the source codes inside the folders. No executable files/data/text files etc required.
iii. Create a Makefile for compilation and add a README file to add your notes/comments/ dependencies etc.
• Copying from other students and/or internet will be considered as a worst form of offence and may be penalized by negative
marking. Therefore, students feeling unable to complete the assignment within deadline should request for help from the
instructor.
If required, the assignments may be evaluated by plagiarism checking tools.

18

You might also like