Unix Scripting: Top Ideas to Write Easily

In UNIX, writing script is the main task. We use Scripts in many places to increase productivity. So my post gives you top ideas on writing scripts.

Tip 1 – Comments in Script

Lines not preceded by a hash ‘#’ character are taken to be Unix commands and are executed. Any Unix command can be used.

For example, the script below displays the current directory name using the pwd command, and then lists the directory contents using the ls command.

# purpose: print out current directory name and contents 

Tip 2 – Writing Variables

The script below shows how to assign and use a variable. In general, shell variables are all treated as strings (i.e. bits of text).

Shells are extremely fussy about getting the syntax exactly right; in the assignment there must be no space between the variable name and the equals sign, or the equals sign and the value.

To use the variable, it is prefixed by a dollar ‘$’ character.

#!/bin/sh # name is a variable 
echo "The name is $name"

You May Like: How to write script in UNIX effectively

Tip 3 – Writing Conditions IF THEN ELSE FI

Conditionals are used where an action is appropriate only under certain circumstances. The most frequently used conditional operator is the if-statement. For example, the shell below displays the contents of a file on the screen using cat, but lists the contents of a directory using ls.

# show script
if [ -d $1 ]
  ls $1
  cat $1

Tip 4 – Looping commands DO WHILE

The simplest looping command is the while command. An example is given below:

# Start at month 1
while [ $month -le 12 ]
# Print out the month number
  echo "Month no. $month"
# Add one to the month number
  month=`expr $month + 1`

Tip 5 – Unix Script an Example

One of the best example of sample script is as follows.

# DOS interpreter. Impersonates DOS as follows:
# DOS command   UNIX equivalent   Action
# cd            cd                Change directory
# dir           ls                List directory contents
# type          cat               List file contents
# del           rm                Delete a file
# ren           mv                Rename a file
# copy          cp                Copy a file

echo "Welcome to the DOS interpreter"
echo "Type Ctrl-C to exit"
# Infinite loop
while [ "forever" ]
# Show DOS prompt; c stops a new line from being issued
  echo "DOS> c"  
# Read in user's command
  read command arg1 arg2
# Do a UNIX command corresponding to the DOS command
  case $command in
      cd $arg1
      cat $arg1
      rm $arg1
      mv $arg1 $arg2
      cp $arg1 $arg2
      echo "DOS does not recognise the command $command"

Here’re some additional examples.

Also Read

UNIX | Scheduling | Tips

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.