Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Topics

Recent Status Updates

View All Updates

- - - - -

Functions, operators, and options

  • Please log in to reply
1 reply to this topic

#1 DarkLordoftheMonkeys


    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 232 posts

Posted 14 November 2009 - 11:12 AM

This is my third tutorial on bash shell scripting. Here I will be talking about some topics I did not go over previously, namely functions, arithmetic operators, typed variables, and how to parse command line options.


A function, as most programmers with experience in other languages know, is a subroutine, a named procedure that can be called repeatedly throughout the script. I personally do not use functions much as my scripts are generally never more than 30 lines long, but programmers writing long scripts that carry out repetitive tasks might find them useful.

There are two syntaxes for declaring functions. The first is one that programmers in Javascript and PHP will probably be comfortable with:

function myfunc

Note that in this case the inputs to the function are not specified. Instead, you use the variables $1, $2, etc. to access the inputs. You may also notice that the function declaration syntax differs from that of control structures in that it uses the curly bracket notation to define a block.

Here is the other notation for functions:


This syntax may be more familiar to some programmers as it uses named variables instead of $1, $2, etc. as its inputs.

A function is called in much the same way that you would call a regular command:

funcname input1 input2;

Typed variables:

Variables can be given types using the declare or typeset builtins. There are four basic data types in Shell: integer, string, array, and function. There is no type for floating point numbers. An operation on two integer type variables that would normally result in a floating point number will be rounded off to an integer.

declare -a variable=value; - declares an array type
declare -f func; - declares the function named func as a variable. This is basically a string that is that function declaration.
declare -i variable=value; - declares an integer type
declare -r variable=value; - declares a read-only variable, or in other words, a constant

Operators in Shell:

Arithmetic operators:

+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment by 1
-- Decrement by 1
** Exponent

Logical operators:

&& Logical AND
|| Logical OR
! Logical NOT

Assignment oparators:
(used without spaces)
= Equals
+= Increase by
-= Decrease by
*= Multiply by
/= Divide by
%= Modulus by
**= Raise to a power

Test operators:
(used with spaces)
-eq Equal to
-ne Not equal to
-gt Greater than
-lt Less than
-ge Greater than or equal to
-le Less than or equal to

Bitwise operator:
<< Bitshift left
>> Bitshift right
<<= Bitshift left by
>>= Bitshift right by
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR

File test operators:

There are also several operators used to test conditions in files. These are used with control statements like if/then.

-a File exists
-d File is a directory
-e File exists
-f File is a regular file
-G You are in the group that owns file
-h File is a symbolic link
-N File was modified since last read
-O You own file
-r You have read permission
-s File exists and is not empty
-w You have write permission
-x You have execute permission
-nt Newer than
-ot Older than


This script deletes all empty files in a directory:

for file in $(ls $1)
	if [ ! -s "$1/$file" ];
		echo "$1/$file is empty.  Removing file.";
		if [ -d "$1/$file" ]
			rmdir "$1/$file";
		elif [ -f "$1/$file" ]
			rm "$1/$file";


Options (inputs beginning with a dash) can be parsed separately from the regular inputs by using the shift builtin. This makes it so that $1=$2, $2=$3, etc. Eventually, the script has its inputs in the right place and knows what options have been set. Here is a trivial script for doing this:

# This script demonstrates how options and inputs
# to the script can be parsed separately.
for param in $*
	case $param in
		-*[ad]* )
			case $param in
				-*a* ) opta="on";;
			case $param in
				-*d* ) optd="on";;
		-* )
			echo "Error: $param is not an option.";
			printf "\a";
# Now the options have been stored for later use,
# while allowing the inputs to be processed.
echo "You entered \"$filename\" as the filename.  Do you wish to proceed?";
if [ $opta = $optx ]
	echo "Option a is turned on.";
	echo "Option a is turned off.";
if [ $optd = $optx ]
	echo "Option d is turned on.";
	echo "Option d is turned off.";
# Now for some "garbage collection".
unset opta;
unset optd;
unset optx;

  • 1
Life's too short to be cool. Be a nerd.

#2 WingedPanther73


    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 14 November 2009 - 01:51 PM

Very nice. +rep
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download