简体   繁体   中英

How to create a function in shell script that receives parameters?

I'm working on a shell script and I have some lines of code that are duplicated (copy pasted, let's say).

I want those lines to be in a function. What is the proper syntax to use?

And what changes shoud I do in order for those functions to receive parameters?

Here goes an example.

I need to turn this:

amount=1
echo "The value is $amount"
amount=2
echo "The value is $amount"

Into something like this:

function display_value($amount) {
    echo "The value is $amount"
}

amount=1
display_value($amount)
amount=2
display_value($amount)

It is just an example, but I think it's clear enough.

Thanks in advance.

function display_value() {
    echo "The value is $1"
}

amount=1
display_value $amount
amount=2
display_value $amount

In a shell script, functions can accept any amount of input parameters. $1 stands for the 1st input parameter, $2 the second and so on. $# returns the number of parameters received by the function and $@ return all parameters in order and separated by spaces.

For example:

  #!/bin/sh
  function a() {
   echo $1
   echo $2
   echo $3
   echo $#
   echo $@
  }

  a "m" "j" "k"

will return

m
j
k
3
m j k

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM