Shell scripting
-----------------------
*Shell script consists of set of commands to perform a task
*all the commands will execute sequentially
SHEBANG --> The shebang is the character sequence #! at the top of a script file,
used to tell the system which interpreter to use to run the script.
syntax -->#!<path-to-interpreter>
| Language | Shebang Line |
| ---------------- | ------------------------ |
| Bash | #!/bin/bash |
| tcsh | #!/bin/tcsh |
| Python 3 | #!/usr/bin/env python3 |
| TCL | #!/usr/bin/env tclsh |
| Perl | #!/usr/bin/perl |
| [Link] | #!/usr/bin/env node |
| Ruby | #!/usr/bin/env ruby |
Methods to run scripts
-------------------------
| Method | Description | Environment Changes
Persist? |
| ------------------ | ----------------------------------- |
---------------------------- |
| `bash [Link]` | Runs using Bash | ❌ No
|
| `./[Link]` | Runs via shebang (needs `chmod +x`) | ❌ No
|
| `source [Link]` | Runs in current shell | ✅ Yes
|
| `. [Link]` | Same as `source` | ✅ Yes
|
| `sh [Link]` | Runs using default shell | ❌ No
|
| `tcsh [Link]` | Runs a tcsh script | ❌ No
|
Loops in tcsh
------------------
[Link]
syntax --> foreach i ($var)
......
end
Ex - echo " Calculating the squares of numbers:"
foreach i (2 4 6 8 10)
set square = `expr $i \* $i`
echo "$i square is $square"
end
[Link]
syntax --> while (condition)
.....
end
Ex - #!/bin/tcsh
set counter = 1
while ($counter <= 5)
echo "Counter: $counter"
set counter = `expr $counter + 1`
end
------------------------------
conditional ststemants
-------------------------------
[Link]
syntax --> if (condition) then
....
endif
Ex - #!/bin/tcsh
echo "Enter a number:"
set num = $< # to read input
if ($num == 0) then
echo "You entered zero."
endif
[Link] else
syntax --> if (condition) then
.....
else
......
endif
Ex - #!/bin/tcsh
echo "Enter a number:"
set num = $<
if ($num % 2 == 0) then
echo "$num is even."
else
echo "$num is odd."
endif
[Link]-elseif
syntax --> if (condition) then
.....
elseif (condition) then
........
else
.....
endif
Ex --> #!/bin/tcsh
echo "Enter a number:"
set num = $<
if ($num < 0) then
echo "$num is negative."
elseif ($num > 0) then
echo "$num is positive."
else
echo "$num is zero." # Technically already printed by the first if block
endif
[Link]
syntax --> switch (string)
case pattern1:
......
breakaw
case pattern2 :
......
breaksw
case pattern3 :
.....
breaksw
default :
.....
breaksw
endsw
Ex - #!/bin/tcsh
echo "Enter a grade (A/B/C/D/F):"
set grade = $<
switch ($grade)
case A:
echo "Excellent!"
breaksw
case B:
echo "Good job!"
breaksw
case C:
echo "You passed."
breaksw
case D:
echo "Needs improvement."
breaksw
case F:
echo "Failed."
breaksw
default:
echo "Invalid grade."
breaksw
endsw