[Techtalk] Bash functions with user-defined parameters
Conor Daly
conor.daly at oceanfree.net
Mon Apr 28 15:42:31 EST 2003
On Mon, Apr 28, 2003 at 05:52:59AM -0700 or so it is rumoured hereabouts,
Berenice thought:
> I've been messing around with bash and want to create a function that
> takes two different integers and increments the first integer by 1,
> until the first integer is the same as the second integer. Eg: if
> there are 2 numbers, 1 and 4, add 1 to the first number until it
> becomes 4.
>
> Now I can do this interactively like this:
>
> #!/bin/bash
> echo "Enter 2 numbers:"
> read num1 num2
> while [ $num1 -le $num2 ]
> do
> echo $num1
> num1=$(( $num 1 + 1 ))
> done
>
> But I'm having trouble making it into a function that executes by
> typing the function name with parameters, eg: myfunction 1 4. Here's
> what I've done so far:
>
>
> #!/bin/bash
> myfunction()
> {
> while [ $1 -le $2 ]
> do
> echo $1
> #problem here...$(( $1 + 1 ))
> done
> }
>
>
> The problem is with the $(( $1 + 1 )) because you can't do $1=$(( $1
> + 1 )). Is there a way to fix this, or should I forget about using
> $1 and $2?
how about:
num1=$1
while [ $num1 -le $2 ]
do
echo $num1
num1=$(( $num1 + 1 ))
# I think this works too... num1=$(( $num1++ ))
done
Now, if you wanted to _change_ the value of $1 in the calling function,
it's a different matter...
Conor
--
Conor Daly <conor.daly at oceanfree.net>
Domestic Sysadmin :-)
---------------------
Faenor.cod.ie
3:38pm up 38 days, 21:14, 0 users, load average: 0.08, 0.02, 0.01
Hobbiton.cod.ie
3:37pm up 38 days, 21:12, 1 user, load average: 0.00, 0.01, 0.00
More information about the Techtalk
mailing list