Five Little Tricks To Achieve The Best Results In UNIX script

The following 5 tips really helpful in writing awesome scripts in UNIX. For serious learners of UNIX scripts, below are the right points to begin with.

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"

> How to write script in UNIX effectively: A most popular course learn at your most free time.

Tip#3- Writing conditions: 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: 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- Sample Script: 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"

You can read online some additional examples here.

Also Read

  1. Best COBOL example with COMPUTE in easy way
  2. Automation The Automation types and job survival in digital age
  3. Artificial Intelligence 5 strong reasons why AI is popular now