functionshellsh

shell script functions arguments/parameters


i'm playing around with basic shell scripts and would like to know how to do the following if possible

i have created a basic script with a function and i want to call it when i type the main command with variables like first name and surname

source ./test.sh; talk $John $Smith

  function talk($firstName, $lastName)
{
        echo "hi! ${firstName} ${lastName}"
}

I cant seem to get it to work,not sure where im going wrong, i've tried reading up but getting confused


Solution

  • This should not be necessary.

    talk() {
       echo "Hi! $1 $2"
    }
    

    defines the function. After a source you can invoke it with

    talk Hans Peterson
    

    In sh variables are not declared with a prefix $, but accessed that way:

    a=5
    echo $a