Unix Basics and TCL Scripting
Unix Basics and TCL Scripting
LANGUAGE
-N HEMA NAGA VAISHNAVI
Introduction
● Introduction to computer systems:
A computer is an electronic device that can be programmed to accept data (input), process it
and generate result (output). A computer along with additional hardware and software
together is called a computer system. A computer system primarily comprises a central
processing unit (CPU), memory, input/output devices and storage devices. All these
components function together as a single unit to deliver the desired output. A computer
system comes in various forms and sizes. It can vary from a high-end server to personal
desktop, laptop, tablet computer, or a smartphone.
● Introduction to OS
All the computer systems have OS installed, it is a program that acts as an Interface between
the system hardware and the user making the tasks easier. It is important software which
runs on a computer and controls the set of instructions and wisely utilizes each part of the
Computer.
● Types of OS
o Windows: It is also used in many offices because it gives you access to productivity
tools such as calendars, word processors, and spreadsheets. It is a graphic user
interface.
o Linux: Server OS for web servers, database servers, file servers, email servers and
any other type of shared server. Designed to support high-volume and multithreading
applications, Linux is well-suited for all types of server applications. Desktop OS for
personal productivity computing. It is command line interface.
o Mac: It works hand in hand with iCloud to keep photos, documents and other stuff
up to date on all your devices. It makes your Mac work like magic with your iPhone
and other Apple devices.
Windows is an OS within which ASCII text file is Linux could be a free and open supply
inaccessible. it’s designed for the people who do OS supported operating system
not have programming ability and can you the OS standards. It provides programming
as an graphic user interface. interface still as programm compatible
with operating system primarily based
systems and provides giant selection
applications.
It is free of cost.
It is costly and needs license. File name is case sensitive.
File name is not case sensitive.
It is less efficient compared to linux. It is most efficient.
It is less secured. It is more secured and used in hacking
based systems.
● Introduction to Linux OS
o It is a free and open-source operating system and the source code can be modified
and distributed to anyone commercially or noncommercially under the GNU
General Public License.
o Initially, Linux was created for personal computers and gradually it was used in
other machines like servers, mainframe computers, supercomputers, etc.
Nowadays, Linux is also used in embedded systems like routers, automation
controls, televisions, digital video recorders, video game consoles, smartwatches,
etc.
o The biggest success of Linux is Android(operating system) it is based on the
Linux kernel that is running on smartphones and tablets. Due to android Linux
has the largest installed base of all general-purpose operating systems. Linux is
generally packaged in a Linux distribution
● The popular Linux distributions are:
o MX Linux
o Manjaro
o Linux Mint
o elementary
o Ubuntu
o Debian
o Solus
● Types of interfaces in OS
o Kernel: It is a lowest level of software to have interface with computer hardware and
its processors. It is a head of OS.
o Shell: It acts as an interface between a user and a kernel.
o Applications: All the activities can be stored into a file or a directory and have it as
further usage.
● Shell:
AS shell acts as an interface between user and a kernel we do all the operations in the
shell using scripting language.
There are many scripting languages like Bash, Csh, Tcsh, Tcl, Perl, Python ..etc;
● Unix commands:
We have few commands in Unix to create a file, directory, editing, copying, pasting and
many more.
All the scripting in shell is done in terminal just as we do in command prompt in
windows OS.
● Let’s list out few commands that are most used in Unix.
a.a.i.1. General syntax of commands:
Command –option <argument>
a.a.i.2. Location of a file or directory:
One should know where our file or directory is located in our system, this could be
represented using two methods.
a.a.i.2.a. Absolute path:
This describes the complete path of our file or directory.
/ = This indicates root and every path should always start root.
The first directory on any system will be “HOME” directory.
Eg: /home/user/pd/sta/timing
b. Relative path:
This uses few symbols to describe “HOME, CURRENT, PREVIOUS” directories.
./ = This indicates current directory
../ = This indicates previous directory
~ = This indicates home directory
Eg: cd ~ -> Changing from current directory to home directory
Eg: cp ../ ./ -> copying previous directory to current directory
TCSH Commands
1. echo $0 = Prints which shell we are working in.
2. which<command/shell> = Prints the absolute path of the installed location of the shell or
the command.
3. To install any package: apt install <package name>
Eg: apt install tcsh
Sudo install –y <package>
Eg: sudo install –y tcsh
4. To change from one shell to other shell we just need to type the shell name.
5. Knowing present working directory
PWD: This command gives the absolute path of the directory we are working in.
6. Changing to another directory : cd
Syntax: cd <path of the directory where we want to change>
Cd - : it will change to the last opened directory.
7. Creating an empty file: touch
Syntax: touch <filename>
8. Creating a directory: mkdir
Mkdir means make directory; it creates an empty directory.
Syntax: mkidr<directoryname>
Mkdir –p directory1/directory2 : This creates a directory2 inside directory1 at one go with
the help of option –p ( -p: parent).
9. Concatenate command:
The command for concatenate is “CAT”
This command helps in creating a file, displaying a file, writing content into a file,
concatenating a file.
Cat >filename : this command creates a file if it does not exist and prompt blinks in next
line expecting to add some information to the file. If a file exists the previously existing
data will be overwritten by the new content.
Cat >>filename : this command creates a file if it does not exist and prompt blinks in next
line expecting to add some information to the file. If a file exists the new content will be
appended to the existing data.
Cat filename : this command only displays the content of the file in the terminal.
Cat –n filename : this command displays the line number and content of the file in the
terminal.
10. Redirectory operators:
>, < ,>> these symbols are called as redirectory operators.
▪ > : outputredirectory operator. This displays content of a file but not in the terminal the
content is redirected to other file and one can view it by opening that file.
If content does not exist in a file it adds but If data is already present it will overwrite.
Syntax : command > command/filename
Eg: cat > filename
Eg: echo “ hello” > file
▪ >> : output redirectory operator. It works as the previous one but it does not overwrite the
content it will append.
Syntax: command >> argument
Eg: cat >> filename
▪ < : input redirectory operator. The output of one command is given as input to the next
command.
Syntax: command <argument>< command <argument>
Eg: cat file < sort file : this sorts the content of the file and this sorted file is an input to the cat
command and displays sorted data in the terminal.
11. Listing command: ls
This command lists out all the files and directories in the current directory or if the path is
specified it displays the all the directories and files of that particular directory.
Eg: drw-r- -r- - 2 userID 4098 jan 1 12:08 directory : This is a directory with 2 directories or
files inside by a user with 4098byte created on jan 1 12:08.
ls –tl : displays long listing output with recently created on the top.
ls –rtl: displays long listing output with recently created on the bottom.
Note: t = time; r = reverse.
12. Quotes:
Eg: set a = 10
Set b = 5
Echo ‘$a,$b’ : output: 10,5
Echo “$a,$b” : output: $a,$b
Set c = `expr $a + $b` : output: 15
` `: command substitution
“ “ : masking
‘ ‘ : to access the variables
13. Tail and Head: It is used to print last 10 lines and 1st 10 lines of a file respectively.
Tail file: it prints last 10 lines of file
Tail -5 file: it prints last 5 lines of file
Head file: it prints 1st 10 lines of file
Head -4 file: it prints 1st 4 lines of file
19. Link: It acts like a string creating pathways for different files and directories in the computer
system. These are capable of creating and storing multiple files in different places referring to
one single file.
There are two types of links: soft link, hard link.
a. Soft link: These are the actual copy of the original file. When any changes is done in
original file or linked file the changes are affected on both the files. If we delete the
original file then the soft linked file will be existing but the content will be erased and the
deleted original file will be blinking and soft linked file will appear in red letters in a black
background this can be seen when one does ls –l.
Syntax: ln –s [target file] [soft link file name]
S indicates its symbiolic i.e. soft link.
To check if link file is created or not :
ls –l is the command to check, the output of this command will be:
lrw-r- -r- - 1 USERID 4098 month date time linkedfile ->originalfile
The linked file appears in skyblue colour.
Syntax: ln –sv [target file] [soft link file name]
V indicates its verbose.
The output of ln –sv [target file] [soft link file] will be soft link file -> original file ; where soft
linked file appears in skyblue colour.
b. Hard link: These are the mirror copy of the original file. When any changes is done in
original file or linked file the changes are not affected on the other file. If we delete the
original file then the hard linked file will be existing and the content will also be existing.
The hard link file name appears in blue background.
Syntax: ln [target file] [hard link file name]
To check if link file is created or not :
ls –l is the command to check, the output of this command will be:
lrw-r- -r- - 1 USERID 4098 month date time linkedfile
The linked file appears in blue colour background.
Syntax: ln –v [target file] [hard link file name]
V indicates its verbose.
The output of ln –v [target file] [hard link file] will be hard link file => original file ; where
hard linked file appears in blue colour background.
20. Unlink : This removes the linked file.
Syntax: unlink <linked file name>
21. Suspend: When we are running some script and it takes more than the expected run time then
suspension of that script can be done with the help of “ctrl + z”. The script still remains in the
background so if one wants to resume that script then “bg” will help but it will resume only
the recent script that has been suspended.
22. “Command <argument>&“ This will work same as ctrl + z and the bg command. So when
one gives this command with & we can continue next script instead of waiting for the
executing command.
23. Fg: foreground command, when one give “fg” command the current running job will showed
on the terminal, upon seeing the job one can give bg so that the job still continues in the
background.
24. To kill a current process we can use “ctrl + c”.
25. Secure shell : ssh
We have to use another server from our server to do our projects and this can be done with
help ssh command.
Syntax :ssh –x <user ID @ server name>
It asks for the assigned password, once it is entered we are taken to the server where we wish
to work.
26. To know the current running process : ps (process status).
The output of ps will be:
<PID >< terminal type><time><command>
27. To kill current active process : kill
Syntax : kill% -9 PID : it forcefully kills the active PID.
28. Jobs: This command is used to list all the jobs that you are running in the background and in
the foreground. If prompt returns without any information it means no jobs are active. This
command only works on Bash, tcsh, ksh and csh shells only.
29. To know disk information:
Staying in the home directory :df –kh ./ : This gives the disk free area of our system or server.
To get each files disk space utilized information: du –sh *
To get the information of the complete team’s files utilized area information: du –u *
3. Awk:
It is used for pattern scanning and processing, it searches one or more files to
see if they contain lines that matches with specified patterns, transforms data
files, produce formatted reports, performs arithmetic operations, conditional
and loop statements, and then perform the associated actions.
AWK is the abbreviated from the names of the developers – Aho, Weinberger
and Kernighan.
Syntax: awk<option> ‘selection criteria{action}’ <input file>
Pre-processing:
This does not require input file, it uses the keyword “BEGIN” where we can
do loops, conditional statements, arithmetic operations using this keyword.
Syntax: awk‘BEGIN{print “text to be printed”}’
Eg: awk‘BEGIN{print “hello”}’
Mathematical operations:
Awk‘BEGIN{print ARGV[1] * ARGV[2]}’ 10 20
Output: 200
To access external variable using awk:
Eg: set a = 10
Set b = 20
Awk –vA=$a -vB=$b ‘BEGIN{print A B}’
Output: 10 20
To access external variables using awk and do arithmetic operation:
Eg: awk –vA=$a –vB=$b ‘BEGIN{print A+B}’
Eg: awk ‘{print ARGV[2]/ARGV[1]}’ $a $b
Output: 2
Accessing external variables without using –v:
Eg: awk ‘{print ARGV[1] ARGV[2]}’ $a $b
10 20
• Record – processing:
It requires input file. It does search operation, it could replace file.
Eg: awk ‘/Hello/{print}’ file
Let say file has:
Hello this is xyz.
Hi this is abc.
Hello world.
Hey dear.
• Post-Processing:
This requires input as file. It used keyword “END” and prints only the last line
of file, if NR is used it prints even the last record number.
Eg: awk‘END{print NR, $0}’ file
Let’s say file has:
And or nand
Xor or
Nor not xnor
Ouput: 3 nor not xnor
Loops in awk:
• For loop:
Syntax: awk‘BEGIN{for(initialization;condition;increment){){print
variable}}’
• Nested loops:
Syntax:
awk‘BEGIN{for(initialization;condition;increment){for(initialization;conditi
on;increment){print variables}}}’
• While loops:
Syntax: awk‘BEGIN{initialization; while(condition) {print increment}}’
Conditional statements:
• If:
Syntax: if (condition) {action}
• If-else:
Syntax: if(condition)(action}else{action}
• If-elseif-else
Syntax: if(condition){action}elseif (condition) {action } else{action}
Control statements:
• Break:
If(condition){break}
Breaks the loop at that condition.
• Continue:
If(condition){continue}
Continues the loop skipping that particular condition.
• Exit:
If(condition){exit}
Exits the loop at that condition.
TCSH scripting
We write our tcsh commands in gvim file.
The first line of the file should be the shell interpreter so that the shell understands on
which shell it has to execute.
#! / path of the shell installed/
Eg: #! /bin/tcsh
#! -> it is known as shell interpreter.
To execute the file in shell we need to first give the execute permission to the file.
To execute we need to use : shell name /path of the gvim file/
Eg : tcsh ./command.tcsh
If we want some particular commands to not be executed use: so all the commands
within if and endif will not be executed.
If 0 then
....
Endif
If we want to execute only few commands and not other commands write “exit” after
the commands that are to be executed so that all the commands below exit will not be
executed.
• Loops:
Foreach:
Foreach variable ($variable)
...
End
While:
Initialization
While(condition)
Increment
End
Conditional statements:
• If(condition) then
....
endif
• If(condition) then
...
Else
...
endif
• If(condition) then
....
Elseif(condition) then
...
Else
...
Endif
• Switch(strng)
Case pattern1:
Breaksw
Case pattern2:
Breaksw
Default:
Breaksw
Endsw
Mathematical operations:
Expr is used to all the maths operation.
Eg: set a 10
Set b 20
Puts [expr $a + $b]
Output: 30
Expr{abs(x)}
Eg: set a -10
Expr{abs($a)}
Output: 10
It prints me the positive values.
Expr{ceil(x)}
It rounds to highest value of given number.
Eg: set a 10.5
Expr{ceil($a)}
Output: 11
Expr{floor(x)}
It rounds to lowest value of given number.
Eg: set a 10.5
Expr{floor($a)}
Output: 10
Expr{double(x)}
It prints me floating value.
Eg: set a 10
Expr{double($a)}
Output: 10.0
Expr {int(x)}
It prints me the integer value of given number.
Eg: set a 10.5
Expr{int($a)}
Output: 10
Expr{min(range of values)}
Eg: expr{min(10 30 9 50)}
Output: 9
Expr{max(range of values)}
Eg: expr{max(10 20 3 50)}
Output: 50
Expr{pow(x,y)}
Eg: expr{2,2})
Output: 4
List operations:
We have few list operations where we can modify a list.
Lindex:
Eg: Set a {10 20 30 40}
Lindex $a 0
Output: 10
The index values of a list starts with 0.
We can access last index of a list using “end.
Lindex $a end
Output: 40
Llength:
It prints me the length of a list.
Eg: set a {10 20 30 40}
Llength $a
Output: 4
Lappend:
It appends a value to the list.
It modifies the original list.
Eg: set a {10 20 30 40}
Lappend a xor
Output: 10 20 30 40 xor
Linsert:
It inserts given value at the given index.
Eg: set a {10 20 30 40 50}
Linsert $a 2 and
Output: 10 20 and 30 40 50
Lsort:
It sorts the given list with respect to ascii character, we can you use few switches to sort.
Eg: set a {10 20 AND and 30 AND 40}
Lsort –increasing –unique $a
Output: 10 20 30 40 AND and
-increasing: it sorts in increasing order
-decreasing: it sorts in decreasing order
-unique: it does not print the repeated values in the list.
Lset:
It sets a value to the given index. It modifies the original list.
Eg: set a {10 20 30 40}
Lset a 2 xor
Output: 10 20 xor 40
Lassign:
It assigns the values in the list to another variable.
Eg: lassign {10 20 30} a b c
Puts “$a $b $c”
Output: 10 20 30
Lreplace:
It replaces the range of values or a value of the list.
Eg: set a {10 20 30 40 50 60 70}
Lreplace $a 0 0 xor
Output: xor 20 30 40
Lreplace $a 2 4 xor
Output: 10 20 xor 60 70
Lreplace $a 1 1
Output: 10 30 40 50 60 70
Lsearch:
It searches given pattern.
Eg:
Lsearch {a b c}.c
Output: 2
Lsearch –all {a b c bba abb c}.c
Output: 2 5
Lsearch –inline {a b c bba abba c abb}b*
Output: b
Lsearch –inline –all {a b c abba bba bab}b*
Output: b bba bab
Lrange:
It prints range of values.
Eg: set a {10 20 30 40 50 60}
Lrange $a 0 0
Output: 10
Lrange $a 0 3
Output: 10 20 30 40
Arrays in tcl:
Arrays are used as single dimension list of values where we can assign it to one variable
there by reducing the memory space.
We can assign values to arrays using two methods:
Conventional method:
Set variable(key/index) value
Eg: set a(ones) {1 2 3 4}
Here in the example “a” is my array name, “ones “ is my key of the array where the given
list gets stored.
1. Associative method:
This is the most used method of assigning values to the array.
There few sets in this method, let’s look at them.
To set values to an array:
Syntax: array set array_name {
Keys {list}
}
Eg: array set numbers {
Ones {1 2 3 4}
Tens {10 20 30 40}
}
To print the array elements:
Syntax: puts stdout $array_name(key)
To print array elements using array:
Syntax: array get array_name : this prints all the keys and their elements.
Syntax: array get array_name key: this prints only the elements of the array of that
particular key.
To print size of the array:
Syntax: array size array_name
To print only the elements of the array:
Syntax: array names array_name
To unset the array:
Syntax: array unset array_name
To check if array exists or not:
Syntax: array exists array_name: if yes it prints 1 if no it prints 0.
Loops in tcl:
For loop:
Syntax: for { initialization } { condition } { increment/decrement } { statement }
Eg: for { set a 1 } { $a <= 5 } { incr a } {puts $a }
Output: 1
2
3
4
5
While loop:
Syntax: initialize while { condition } { statement ; increment/decrement}
Eg: set a 1
while { $a <= 5 } { puts $a incr a}
Output: 1
2
3
4
5
Foreach loop:
Syntax: foreach loop_variable variable {statement}
Eg: set a {10 20 30 40}
Foreach i $a {
Puts $i
}
d. Catch: It captures errors. If we run a set of commands from a file and some error has
occurred, capturing those errors will be helpful so that we can grep the error and correct the
command.
syntax: catch command arguments
if {[catch {command arg..} result ] } {
puts stderr $result
} else {
puts “no errors”
}
Conditional statements:
If { condition } {
Statement
}
If { condition } {
Statement
}
If { condition } {
Statement
} elseif { condition } {
Statement
} else {
Statement
}
If { condition } {
Statement
} else {
Statement
}
Switch string {
Statement 1
}
String 2 {
Statement 2
}
Default {statement}
}
}
Output: x is 1
Y is 1
Y is 4
X is 4
Therefore, initially x is 1 and is printed; but when “test” is called the compilation goes to
definition and sees for value of y but it holds the pre-existing value of x into y and only
when compilation sees that y is declared with 4 then it sees for printing option and prints
again y with value of 4 and this being carried to x and x is declared with value 4.
Global scope:
The variable is called outside the definition.
Syntax: global <variable>
Eg: proc test { } {
Global x
Puts “x is $x”
Proc nested { } {
Global x
Puts “x is $x”
}
}
Set x 1
Test
Nested
Puts “x is $x”
Output: x is 1
X is 1
X is 1
w: It is used to write the content into the file, it creates a file if it does not exists, if
exists it over writes the content.
a: It is used to append content to the file, the file should exist.
r+: It is used open the file in read mode and even helps in writing content in the file.
The file should be existing.
w+: It is used to write and read the file. If file does not exist it creates the file and
overwrites the data.
a+: It is used to append the content on to the file and open in read mode. It creates the
file if it does not exist.
Regular expressions:
It is useful when listing operations during search and replace.
regexp: It is used for matching patterns in a string.
regsub: It is used to replace, search and modify a file.
regexp:
syntax: regexp <options> “<pattern match>” “<string to match>” variable
output of regexp will be the numeric value of how many matches are found.
The most used options are : -inline, -all, -not.
regsub:
syntax: regsub <option> “<pattern match>” “<string to match>” “<string to replace>”
<variable>
output of regsub is the numeric value of how many replacements have occurred.
Example on both regexp and regsub:
Set fh [open “file.txt” r]
Set fp [open “file1.txt” w]
While { [gets $fh line] >= 0} {
If { [regexp –all –inline “pass” $line a] >= 1 } {
Puts $a
Puts [regsub –all “pass” $line “p” b]
Puts $b
} else {
Puts $fp $b
}
}
Close $fh
Close $fp
String first: It is used to search a word in string and access only the first occurrence.
Syantx: string first “word” “string”
If the word is found it prints 1 or 0, if not -1
Index: It prints me the number of indexes of the string, i.e. the number of characters of a
string. It even includes space as one character.
Syntax: string index “string”
Length: The output of string length is similar to gets command. It prints the total length.
Syntax: string length “string”
Match pattern:
It matches the pattern with respect to the index. If the exact is not matched then it prints -1
if matches it prints 1.
Syntax: string “string1” “string2”
Trim:
Trims from both sides
Syntax: string trim “string” “trimming word”
To trim left side: trimleft
To trim right side: trimright