how to declare variables and use in scripts

March 17, 2011 at 22:47:34
Specs: unix
As i am new to unix so having a lot of confusions on using and assigning variables.
So i want to know how to declare variables like we normally declare in other normal programs
and use that variable inside the shell script such as inside the functions or as i have written awk program and i want to declare a variable string and want to use that variable in the script.
so help me out of this and if possible explain it with a small example.

See More: how to declare variables and use in scripts

Report •

#1
March 18, 2011 at 07:37:34
Below is a script I wrote for an assignment while taking a UNIX course. It shows how to declare and use variables. You should be able to copy/paste it and run it once you 'chmod' the file you save it in.

#!/bin/sh
# if run with no arguments, inform user of error
if [ $# = 0 ]
        then
                echo "Usage: $0 number-list"
                exit 1
fi

sum=0   # running sum initialized to zero
count=0 # count the count of numbers passed as arguments

while [ $# != 0 ]
do
  sum=`expr $sum + $1`     # add the next number to the running sum
  count=`expr $count + 1`  # update the count of the numbers added so far
  shift
done

# display the final sum
echo "The sum of the given $count numbers is: $sum"
exit 0

It matters not how straight the gate,
How charged with punishments the scroll,
I am the master of my fate;
I am the captain of my soul.

***William Henley***


Report •

#2
March 18, 2011 at 08:57:50
Here is a link you might find useful:

and another:


Report •

#3
March 20, 2011 at 10:24:34
Thanks for the site it is very helpfull, and thanks to u also Curt R.

Report •
Related Solutions


Ask Question