8.) Bash Shell-2jdudhdbg
8.) Bash Shell-2jdudhdbg
Arithmetic Operators
Arithmetic Operators
Relational • These operators compare two values. The comparison is
done inside [ ] or [[ ]] for strings and (( )) for
(Comparison) integers.
Operators
Relational (Comparison) Operators
Logical
Operators
• Logical operators are used
to combine multiple
conditions in conditional
expressions. These are
typically used with if,
while, until, or inside [
], [[ ]], or (( )).
• Bitwise operators perform bitwise calculations on
Bitwise integers. They are typically used in (( )) arithmetic
contexts.
Operators
Bitwise Operator
• These operators are used to assign values to variables.
Assignment Operators
Conditional (Ternary) Operator
• Although Bash doesn't have a traditional ternary operator, you can simulate it with expr or
within (( ))
Double [[ ]] and Single Brackets [ ]
• Key Differences and When to Use Each
1. Compatibility:
▪ Use [ ] if you need POSIX compatibility or are working in a script that needs to run on a
variety of Unix-like systems.
▪ Use [[ ]] if you are writing a script specifically for Bash and want to take advantage of
its extended features.
2.Logical Operators:
▪ Use [ ] for simple logical conditions with -a and -o.
▪ Use [[ ]] for more complex logical conditions with && and ||.
3.String Comparisons:
▪ Use [ ] for basic string comparisons.
▪ Use [[ ]] for advanced string comparisons and pattern matching
Double [[ ]] and Single Brackets [ ]
4. Pattern Matching:
o Use [ ] for simple comparisons.
o Use [[ ]] if you need pattern matching with =~ (regular expressions).
5. Error Handling:
o Use [ ] if you prefer traditional, more portable scripting.
o Use [[ ]] for enhanced functionality and easier syntax, but remember it's
not POSIX compliant.
• Note:
o Single Brackets [ ]: Use for basic, POSIX-compliant scripting where
portability is important.
o Double Brackets [[ ]]: Use for more advanced Bash scripting where
additional features and flexibility are beneficial.
For Writing Mathematical Expression in Bash
Shell
• Bash doesn't directly support floating-point arithmetic,
• It provides various methods to handle integer arithmetic.
• For more advanced arithmetic operations, external tools like
o bc and awk can be used to handle both integer and floating-point numbers.
• To write and evaluate mathematical expressions in Bash:
• Breakdown:
o ls -l: List files with details.
o sort -k5 -n: Sort by the fifth column (file size) in numerical order.
o tail -n 5: Display the last 5 entries (largest files).
Advanced Pipe Usage Examples
• Display network connections:
o Using netstat to display network connections and grep to filter
connections using the HTTP port (80).
• Breakdown:
o cat /var/log/syslog: Display the system log.
o grep "error": Filter lines containing "error".
o sort | uniq -c: Count and display unique error messages.
o sort -nr: Sort the errors by frequency, in descending order.
Error Handling in Pipes
• In Bash, pipes only capture the exit status of the last command in the
chain.
• However, sometimes you may want to know if any command in the pipe
failed.
• Use set -o pipefail to catch errors in any command within a pipe:
• If any of the commands in the pipeline fail, the pipeline as a whole will fail,
and you can handle the error accordingly.
1. Used to pass information to a script when it is executed.
Command line 2. Bash provides a set of special symbols to handle these command-
line arguments.
arguments in Bash 1. $0 Represents the name of the script itself (the command
used to invoke the script).
Script • When the below script executed as ./myscript.sh, the output
will be:
• The script name is: ./myscript.sh
2. $1, $2, $3, …
• Description: These represent the positional parameters.
$1 is the first argument, $2 is the second argument, and
Command line so on.
arguments in Bash • If the below script is executed as ./myscript.sh arg1
arg2, the output will be:
Script First argument: arg1
Second argument: arg2
3. $#
Command line • Description: Represents the total number of
command-line arguments passed to the script.
arguments in Bash
• If the below script is executed as ./myscript.sh arg1
Script arg2 arg3, the output will be:
• Total number of arguments: 3
5. $*
Command line • Description: Expands to all the arguments passed
arguments in Bash to the script as a single word. Unlike $@, $* treats all
arguments as one string.
Script • If the below script is executed as ./myscript.sh arg1
arg2 arg3, the output will be:
All arguments as a single string: arg1 arg2 arg3
$@ vs $*
6. $?
Command line • Description: Represents the exit status of the last
arguments in Bash executed command. If the previous command was
successful, $? will be 0. If the command failed, $? will
Script be a non-zero value.
• If the below script is executed and the ls command fails, the
output will be something like:
Exit status: 2 (or another non-zero value).
7. $$
Command line • Description: Represents the process ID (PID) of
arguments in Bash the script itself.
Script • If the below script is executed
• The output will be the PID of the running script.
8. $!
Command line • Description: Represents the process ID of the
arguments in Bash last background command.
Script • The output of the below script will show the PID
of the sleep 10 command that was sent to the
background.
9. $-
Command line
• Description: Displays the current options set for
arguments in Bash the shell.
Script • The output of the below script will display the
current shell options like himBH.
9. $-
Command line
• Description: Displays the current options set for
arguments in Bash the shell.
Script • The output of the below script will display the
current shell options like himBH.
10. shift
Command line • Description: Shifts the positional parameters to
arguments in Bash the left, so $2 becomes $1, $3 becomes $2, and
so on.
Script • After using shift, the first argument $1 is lost,
and $2 takes its place.
Summary of Command-Line Argument Symbols
Redirection
1. Redirecting Standard Output (stdout)
• Redirect standard output to a file (overwrite):
• Searches for all .txt files in the root directory. Both the results and
any error messages (e.g., permission denied) are written to
output_log.txt.
Redirection
3. Redirecting Both Standard Output and Error
• Redirect both stdout and stderr to a file (append):
• Append both:
Redirection
4. Redirecting Input
• Redirect input from a file:
• Suppresses both the output and error messages from the find
command.
Cron Job Scheduling in Linux
Cron Job Scheduling
• A way to automatically run tasks at specified times or intervals.
• It’s widely used for repetitive tasks like backups, updates, and system
maintenance.
• In Linux, cron jobs are managed using the cron daemon
o Which checks the /etc/crontab file,
o The /etc/cron.d/ directory, and
o Users' crontab files to execute scheduled commands.
Key Components of a Cron Job
1. Minute (0 - 59)
2. Hour (0 - 23)
3. Day of the Month (1 - 31)
4. Month (1 - 12)
5. Day of the Week (0 - 7) where both 0 and 7 represent Sunday.
6. Command: The script or command you want to run.
Key Components of a Cron Job
Each field can be set to:
• A specific value (e.g., 5 for 5 minutes).
• A wildcard (*) meaning "every possible value" (e.g., every minute,
every hour).
• Intervals using / (e.g., */15 means "every 15 minutes").
• Ranges using - (e.g., 1-5 for Monday to Friday).
• Lists using commas (e.g., 1,15 means on the 1st and 15th).
Crontab Syntax
• The basic syntax for a cron job entry is:
Example Cron Jobs
• Run a backup script every day at midnight:
• This cron job will execute on the first day of every month at 10 PM.
Example Cron Jobs
• Run a cleanup script every 5 minutes between 9 AM and 5 PM,
Monday to Friday:
• This job runs the script exactly at midnight on New Year's Day.
Special Strings for Scheduling
• There are shorthand strings for common cron schedules:
1. @reboot: Run the command once, at startup.
2. @yearly or @annually: Run the command once a year (0 0 1
1 *).
3. @monthly: Run the command once a month (0 0 1 * *).
4. @weekly: Run the command once a week (0 0 * * 0).
5. @daily or @midnight: Run the command once a day (0 0 *
* *).
6. @hourly: Run the command once an hour (0 * * * *).
Example using • To run a script every time the system starts:
shorthand:
User-Specific Crontab
• Each user can manage their own cron jobs using the crontab
command. To edit a user-specific crontab file, use:
• This opens a file where you can add cron jobs without specifying the
user (unlike in /etc/crontab).
Commands for Cron
• To list all your cron jobs:
o This will run the system update script as the root user at 2:30 AM daily.
Troubleshooting Cron Jobs
• Check Logs:
o Output from cron jobs is typically logged in /var/log/syslog or
/var/log/cron. Check these logs to troubleshoot failed jobs.
o Permissions: Make sure the scripts have execute permissions. Run chmod +x
/path/to/script.sh if necessary.
o Full Paths: Always use full paths for executables and files in your scripts, as
cron may not have the same environment as your shell.