Sunday, 17 April 2016

What is and How to do Shell programming ?


Shell scripting skills have many applications, including :
Ability to automate tasks, such as Backups, Administration tasks, Periodic operations on a database via cron, Any repetitive operations on files 

Example 1 : Store the following in a file named simple.sh and execute it
#!/bin/sh
# Show some useful info at the start of the day
date
echo Good morning $USER
cal
last | head -6

Shows current date, calendar, and a six of previous logins.
Notice that the commands themselves are not displayed, only the results.

Example 2 : Storing File Names in Variables
#!/bin/sh
# An example with variables
filename="/etc/passwd"
echo "Check the permissions on $filename"
ls -l $filename
echo "Find out how many accounts there are on this system"
wc -l $filename

Now if we change the value of $filename, the change is automatically propagated throughout the entire script.

Example 3 : Performing Arithmetic
Backslash required in front of '*' since it is a filename wildcard and would be translated by the shell into a list of file names.
You can save arithmetic result in a variable.
#!/bin/sh
# Perform some arithmetic
x=24
y=4
result='expr $x \* $y'
echo "$x times $y is $Result"

No comments:

Post a Comment

Note: only a member of this blog may post a comment.