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

I am working on a shell script, and I have several lines of code that are duplicated (copy, say).

I want these lines to be in a function. What is the correct syntax?

And what shoud changes do I make so that these functions can receive parameters?

Here is an example.

I need to enable this:

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

In something like this:

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

This is just an example, but I think it is clear enough.

Thanks in advance.

+6
source share
2 answers
 function display_value() { echo "The value is $1" } amount=1 display_value $amount amount=2 display_value $amount 
+11
source

In a shell script, functions can accept any number of input parameters. $ 1 means the first input parameter, $ 2 means the second, etc. $ # returns the number of parameters received by the function, and $@ returns all parameters in order and is separated by spaces.

For instance:

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

will return

 m j k 3 mjk 
+10
source

Source: https://habr.com/ru/post/898636/


All Articles