Version 13 (modified by 2 years ago) ( diff ) | ,
---|
Hands-On
Linux programming (scripting)
Shell Scripting is the language of the linux terminal. Shell scripts are sometimes referred to as “shebang” which is derived from the “#!” notation. Shell scripts are executed by interpreters present in the linux kernel. Interpreters include: bash, csh, zsh e.t.c. Most popular of which is bash.
Typical operations performed by shell scripts include file manipulation, program execution, and printing text.
How to Write Shell Script in Linux/Unix
- Create a file using a vi editor(or any other editor). Name script file with extension . sh.
- Start the script with #! /bin/sh.
- Write some code.
- Save the script file as filename.sh.
- For executing the script type bash filename.sh.
File Color : Executable scripts appear in a different colour from rest of the files and folders.
Let's start to have some experience on scripting
Simple Script for newbies
First we have to create a text file
$cat > hello.sh
And create the content in it
#!/bin/sh echo 'Hello World'
#!/bin/sh
is "how to run" the program.
echo 'Hello World'
is "what to do" in the script
Then make the file executable
$ chmod +x hello.sh
And run the executable file
$./hello.sh
Output:
Hello world
Make yourself familiar with man man
and man apropos
on the shell. It will need for your self-tutoring.
Let's make this little advanced
How to define variables
Variables can be defined using the syntax variable_name=value
. To get the value of the variable, add $
before the variable
#!/bin/bash # A simple variable example greeting=Hello name=world echo $greeting $name
Arithmetic Expressions
These are the operstors supported by bash for mathematical calculations.
+ addition - subtraction * multiplication / division ** exponentiation % modulus
Numerical expressions can also be calculated and stored in a variable using the syntax below:
value=$((expression))
#!/bin/bash var=$((3+9)) echo $var
How to read user input
Sometimes user input are needed to perform relevant operations.
In bash, user inputs are taken using the read
command.
read variable_name
To prompt the user with a custom message, use the -p
flag.
read -p "Enter your age" variable_name
Numeric Comparison logical operators
Comparison is used to check if statements evaluate to true or false.
Equality num1 -eq num2 is num1 equal to num2 Greater than equal to num1 -ge num2 is num1 greater than equal to num2 Greater than num1 -gt num2 is num1 greater than num2 Less than equal to num1 -le num2 is num1 less than equal to num2 Less than num1 -lt num2 is num1 less than num2 Not Equal to num1 -ne num2 is num1 not equal to num2
Syntax:
if [ conditions ] then commands fi
Conditional Statements (Decision Making)
Conditions are expressions that evaluate to a boolean expression (true or false). To check conditions, we can use if
, if-else
, if-elif-else
and nested conditionals.
Looping and skipping
For loops allow you to execute statements a specific number of times.
Looping with numbers:
#!/bin/bash for i in {1..5} do echo $i done
Looping with strings:
#!/bin/bash for X in cyan magenta yellow do echo $X done
While loop
While loops check for a condition and loop until the condition remains true. We need to provide a counter statement that increments the counter to control loop execution.
#!/bin/bash i=1 while [[ $i -le 10 ]] ; do echo "$i" (( i += 1 )) done
Reading files:
Suppose we have a file sample_file.txt as shown below:
#!/bin/bash LINE=1 while read -r CURRENT_LINE do echo "$LINE: $CURRENT_LINE" ((LINE++)) done < "sample_file.txt"
How to execute commands with back ticks
If you need to include the output of a complex command in your script, you can write the statement inside back ticks.
syntax:
var= ` commands `
Example: Suppose we want to get the output of a list of mountpoints with tmpfs in their name. We can craft a statement like this: df -h | grep tmpfs.
#!/bin/bash var=`df -h | grep tmpfs` echo $var
How to Automate Scripts by Scheduling via cron Jobs
Cron is a job scheduling utility present in Unix like systems. Jobs can be scheduled to execute daily, weekly, monthly or in a specific time of the day. Automation in Linux heavily relies on cron jobs.
Below is the syntax to schedule crons:
# Cron job example * * * * * sh /path/to/script.sh
Here, * represent represents minute(s) hour(s) day(s) month(s) weekday(s), respectively.