230 Linux LectureSlides.pptx
230 Linux LectureSlides.pptx
Scripting
Dr. Shak Hossain
Jan 16, 2025
How about you?
wc bash emacs
● Bird’s eye view
multitasking
tcsh
cat device file grep
access
Hardware system
sh
Kernel awk
sort
Shell
Utilities
Who is Linux?
~1991
Where is Linux?
● World Wide Web
○ 67% of the world’s web-servers run Linux (2016)
● Research/High-Performance Compute
○ Google, Amazon, NSA, 100% of TOP 500 Supercomputers.
● Modern Smartphones and devices
○ The Android phone
○ Amazon Kindle
○ Smart TVs/Devices
Why Linux?
● Free and open-source.
● Powerful for research data centers
● Personal for desktops and phones
● Universal
● Community (and business) driven.
Remote Server
Connecting from
Different Platforms
SSH X-Win SFTP
Microsoft MobaXterm
Windows https://mobaxterm.mobatek.net
● X-Windows: XQuartz
○ Download: https://www.xquartz.org/ (Note: This install requires a logout.)
● Provides:
○ Built-in commands
○ Programming control structures
○ Environment variables
username@hostname ~]$
For more information about any command, use man or info (e.g. “man ls”)
Commands: Hands-On
● After you connect, type
○ whoami # my login
○ hostname # name of this computer
○ echo “Hello, world” # print characters to screen
○ echo $HOME # print environment variable
○ echo my login is $(whoami) # replace $(xx) with program output
○ date # print current time/date
○ cal # print this month’s calendar
○ shazam # bad command
Commands: Hands-On Options (Lab)
● After you connect, type
○ whoami # my login
○ hostname # name of this computer
○ echo “Hello, world” # print characters to screen
○ echo $HOME # print environment variable
○ echo my login is $(whoami) # replace $(xx) with program output
○ date # print current time/date
○ cal # print this month’s calendar
○ shazam # bad command
Commands: Hands on Options (Lab)
● Read Chapter 2
○ 2.1 Login
○ 2.2 Changing Password (passwd)
○ 2.3 Picking Secure Password
○ 2.4 Who are You? (whoami, who am i, id, users, who, )
○ 2.5 What is everyone doing on the computer (w)
○ 2.6 Checking current date and time (time, date)
● Read Chapter 10
○ 10.1 Editing the Unix way (vi, :q, vi filename, :q!, )
Commands: Hands-On Options
● Commands have three parts; command, options and arguments/parameters.
Example: cal –j 3 1999. “cal” is the command, “-j” is an option (or switch),
“3” and “1999” are arguments/parameters.
… at its heart is the idea that the power of a system comes more from the
relationships among programs than from the programs themselves. Many
UNIX programs do quite trivial things in isolation, but, combined with other
programs, become general and useful tools.
Commands: Selected text processing utilities
● awk Pattern scanning and processing language
● cat Display file(s)
● cut Extract selected fields of each line of a file
Compare two files Just a few of the
● diff
Search text for a pattern commands for
● grep
Display the first part of files text processing
● head
● less Display files on a page-by-page basis
● sed Stream editor (esp. search and replace)
● sort Sort text files
● split Split files
● tail Display the last part of a file
● tr Translate/delete characters
● uniq Filter out repeated lines in a file
● wc Line, word and character count
Variables and Environment Variables
● Environment variables are shared with programs that the shell runs.
Bash variables
● To create a new variable, use the assignment operator ‘=‘
● BASH built-ins
○ A little different from other commands
○ Just type the command ‘help’
○ Or ‘man bash’
We use pathnames to refer to files and directories in the Linux file system.
● Examples:
○ cd /usr/local Change directory to /usr/local/lib
○ cd ~ Change to home directory (could just type ‘cd’)
○ pw Print working (current) directory
d
○ cd .. Change directory to the “parent” directory
○ cd / Change directory to the “root”
○ ls –d pro* Listing of only the directories starting with “pro”
The ls Command
● Useful options for the “ls” command:
○ ls -a List all files, including hidden files beginning with a “.”
○ ls -ld * List details about a directory and not its contents
○ ls -F Put an indicator character at the end of each name
○ ls –l Simple long listing
○ ls –lR Recursive long listing
○ ls –lh Give human readable file sizes
○ ls –lS Sort files by file size
○ ls –lt Sort files by modification time (very useful!)
Some Useful File Commands
● cp [file1] [file2] copy file
● mkdir [name] make directory
● rmdir [name] remove (empty) directory
● mv [file] [destination] move/rename file
● rm [file] remove (-r for recursive)
● file [file] identify file type
● less [file] page through file
● head -n N [file] display first N lines
● tail -n N [file] display last N lines
● ln –s [file] [new] create symbolic link
● cat [file] [file2…] display file(s)
● tac [file] [file2…] display file in reverse order
● touch [file] update modification time
● od [file] display file contents, esp. binary
Manipulating files and directories
● Examples:
○ cd # The same as cd ~
○ mkdir test
○ cd test
○ echo ‘Hello everyone’ > myfile.txt
○ echo ‘Goodbye all’ >> myfile.txt
○ less myfile.txt
○ mkdir subdir1/subdir2 # Fails. Why?
○ mkdir -p subdir1/subdir2 # Succeeds
○ mv myfile.txt subdir1/subdir2
○ cd ..
○ rmdir test # Fails. Why?
○ rm –rf test # Succeeds
Symbolic links
● Sometimes it is helpful to be able to access a file from multiple locations
within the hierarchy. On a Windows system, we might create a “shortcut.” On
a Linux system, we can create a symbolic link:
● Examples:
○ find ~ -name bu –type d # search for “bu” directories in ~
○ find . –name my-file.txt # search for my-file.txt in .
○ find ~ -name ‘*.txt’ # search for “*.txt” in ~
● Quiz:
○ Can you use find to locate a file called “needle” in your haystack
directory?
○ Extra credit: what are the contents of the “needle” file?
Processes & Job Control
Processes and Job Control
● As we interact with Linux, we create numbered instances of running programs
called “processes.” You can use the ‘ps’ command to see a listing of your
processes (and others!). To see a long listing, for example, of all processes
on the system try:
● To see all the processes owned by you and other members of the class, try:
[username@scc1 ~]$
mycommand & ← process id
[1] 54356
[username@scc1 ~]$
Process Control Practice
● Let’s look at the “countdown” script, in your scripts folder for practice
● Also, try running ‘jobs’ to see any jobs running in the background from this
bash shell.
● To kill the job, use the ‘kill’ command, either with the five-digit process id:
○ kill 54356
● Or, you can use the job number (use ‘jobs’ to see list) with ‘%’:
○ kill %1
Backgrounding a running job with C-z and
‘bg’
● Sometimes you start a program, then decide to run it in the background.
▪ Debian/RedHat/SUSE/…
• The major difference is the software package management on these distros.
Structure of Linux OS
Linux
Shell
• Here is where you • User software
start interacting with and applications
the OS Supplement • High-level programs
• Multiuser environments
al
Software
Core
Linux
Tools
• OS core commands
• System-level programs
• GNU tools • Process/Thread
• Compilers scheduling
Linux
• Memory Management
Kernel • File and I/O management
• Device drivers
• System calls
Linux Shell
What is the shell?
▪ The shell is a program that takes commands from user’s keyboard and passes
them to the operating system to execute.
• Many shell programs are available for Linux:
• bash, sh, csh, tcsh, ksh, zsh, …
• For this tutorial, we will use bash, but other shells are conceptually similar
quanah:$ command
What is Terminal?
▪ Terminal is a program that opens in a window and lets users interact with the
shell.
Working with
Files and
Directories
Understanding Linux Directory Structure
/
boot /
etc /boot
tmp /etc
hom
/tmp
/home
e
mydi /home/mahmadia
mahmadi /home/mahmadia/mydir
ra
/home/eraider
vareRaider
/var
lustr
/lustre
e
/lustre/work
work
/lustre/scratch
.. scratc
Basic Directory Operations
Where am I?
▪ pwd command to print working
directory
quanah:$ pwd
/home/username
directory
quanah:$ cd my_new_dir
▪ ls -l show file
details
quanah:$ ls -l
▪ Always starts with / and goes all the way to the file or directory
• For instance:
quanah:$ cat /home/mahmadia/mydir/file1.txt
5. Now create a new directory under the “exercise1” directory and name it
“subdir1”.
6. Go into the “subdir1” and try to print the content of “test1.txt” on your terminal.
7. Return to the “exercise1” directory and count the number of lines in “test1.txt”.
File and Directory Operations
Copy Files and Directories:
▪ cp command to make a copy of a file(s) or directory(s)
• -r: Recursively copy the directories and subdirectories as well
File and Directory Operations
Move/Rename Files and Directories:
▪ mv command to make a copy of the source file(s) and
directory(s) into the destination and remove the source at the end.
• Can be used for renaming a file/directory as well
File and Directory Operations
Deleting Files and Directories:
▪ rm command to remove file(s) and directory(s) permanently
• Removing files and directories by this command may not be recovered
easily (This is an exception for /home directory on HPCC clusters)
▪ If you set write permission for a directory, you can (create/delete) new
entries
▪ If you set read permission for a directory, you can list (ls) the contents
▪ If you set execute permission for a directory, you can (cd) into the directory
Linux Essential Commands 2
File/Directory Ownership and Permission Examples:
▪ chmod command changes the rwx mode bits of a file or directory
• +/-: adds or removes the mode bits
• u: Sets the permissions for the owner of the file/directory
• g: Sets the permissions for the group that the owner belongs to
• o: Sets the permissions for the other users
• a: Sets the same permissions for user/group/other
Linux Essential Commands 2
File/Directory Ownership and Permission:
▪ With stat or ls –l commands you can check the ownership
and permissions of a file or directory
1. Check the manual of the “man” command and see what type
of manuals are available on Linux
Coming in Part 2 of this Training …
Part 2: Introduction to more advanced topics in Linux
❖ Linux Essential Commands (Part 2)
• -r : Add the directories and subdirectories contents into the zip file
quanah:$ ls
mydir
test1.txt
quanah:$ zip -r archive.zip ./*
adding: ./test1.txt (deflated
62%) adding: ./mydir/ (deflated
0%) quanah:$ ls
archive.zip mydir test1.txt
Linux Essential Commands 2
Compression and File Packaging:
▪ unzip command lists and extracts the contents of a zipped
file
• -l : Lists the contents of a zipped file
quanah:$
ls
archive.zi
p
quanah:$ unzip
archive.zip quanah:$ ls
archive.zip mydir test1.txt
Linux Essential Commands 2
Compression and File Packaging:
▪ Other compression commands available in Linux
Exercise #5
This is a Linux text editor exercise
We finally made it!
5. Save the file and exit
6. Try to display the contents of the file on your screen
7. Change the permission of the file as below:
• Set read/write permission for the owner
• Set read-only permission to your group
• Give a read-only permission to user mahmadia and then remove it.
Environment
Variables in
Linux
Linux Environment Variables
What is the environment variable?
▪ Environment Variables stores any user-defined or system-defined information
that can be accessed within the shell.
▪ Environment Variables are useful for passing data to programs or being used in
shell scripts.
▪ Defining a variable is very simple (do not put spaces around = symbol)
quanah:$ VAR_NAME=“This is a variable”
▪ You can add a directory into the PATH variable of your own
environment
quanah:$ export PATH="/home/username/bin:$PATH"
/home/username/bin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin
export WORK=/lustre/work/mahmadia
export
SCRATCH=/lustre/scratch/mahmadia
export PATH=“$PATH:$WORK/bin”
W9
Scripting
Mar 11, 2025
Bash Scripting
#!/bin/bash
echo "Hello, World!"
$chmod +x script.sh
$./script.sh
Variables in Shell Script
Variables store data for reuse:
name="Linux"
echo "Welcome to $name!"
## Solution:
#!/bin/bash
read name
## Solution:
#!/bin/bash
file="example.txt"
if [ -e "$file" ]; then
else
fi
Comparison Operators
Comparison operators:
● -eq (equal), -ne (not equal)
● -gt (greater than), -lt (less than)
● -ge (greater than or equal), -le (less than or equal)
Scripting: For Loop Structure
for VARIABLE in 1 2 3 … N; do
…
done
While Loop:
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
((count++))
done
Scripting: For Loop Example
## Problem: Write a shell script that calculates the sum of integers from 1 to N
using a loop.
## Solution:
#!/bin/bash
read N
sum=0
sum=$((sum + i))
done
## Solution
#!/bin/bash
file="inputfile.txt"
if [ -e "$file" ]; then
else
fi
Scripting: Switch Case
## Problem: Write script to build a simple calculator
#!/bin/bash
echo "Enter two numbers: "
read a
read b
#input type of operation
echo "Enter your choice: "
echo "1. Addition"
echo "2. Subtraction"
echo "3. Multiplication"
echo "4. Division"
read ch
#Acting on the user input
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
#Printing result
echo "Result: $res"
Functions in Shell Scripting
Defining and calling a function:
function greet {
echo "Hello, $1!"
}
greet "User"
Defining a Function in Bash
function function_name { function_name() {
# Commands to execute echo "Hello from function"
echo "Hello from function" }
}
Calling a Function
function_name #!/bin/bash
threshold=80
Steps:
ping_servers
Function 4 - User Interaction
#!/bin/bash
Objective:
while true; do
Write a script with a menu-driven
echo "1) Check disk usage"
interface using case.
echo "2) List active users"
echo "3) Show system uptime"
Steps:
echo "4) Exit"
read -p "Enter your choice: " choice 1. Display a menu with the
following options:
case $choice in ○ Check disk usage
1) df -h ;; ○ List active users
2) who ;; ○ Show system uptime
3) uptime ;; ○ Exit
2. Use a while loop to keep the
4) echo "Exiting..."; break ;;
menu running until the user
*) echo "Invalid option! Try again."
exits.
;;
esac
done
File Handling
Reading from a file:
Writing to a file:
echo "This is a test" > output.txt
Scripting: Read input File
## Problem: Create a script that searches for a specific word in a file and
counts its occurrences.
## Solution:
#!/bin/bash
read target_word
read filename
## Solution
#!/bin/bash
input_file="input.txt"
output_file="output.txt"