Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass positional parameters to a function

Tags:

bash

shell

I was trying things with bash scripts. I made this simple script

#!/bin/bash

function myfun()
{
    for item in `seq 1 5`
    do
        echo "$item $1 $2"
    done
}
myfun

but no luck. If I change it like this as below, everything seems to be fine,

#!/bin/bash

a=$1
b=$2

function myfun()
{
    for item in `seq 1 5`
    do
        echo "$item $a $b"
    done
}
myfun

It looks like arguments (positional parameters) do not work inside function in shell. Am I doing any mistake? I am still learning things. So can you explain why is it so?

like image 915
sourav c. Avatar asked Feb 14 '26 23:02

sourav c.


1 Answers

It's the function not the loop:

function myfun()
{
    for item in `seq 1 5`
    do
        echo "$item $1 $2"
    done
}

# Pass all of the script's parameters to the function,
# as if writing  myfun "$1" "$2" "$3"..
myfun "$@"
like image 138
cforbish Avatar answered Feb 16 '26 13:02

cforbish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!