Bash script arguments into a function

How to pass arguments into a function? How to Bash all arguments into a function? Bash script the essential for DevOps Roles.
Use variable $1, $2, $3 …$n to access argument pass to the function.

Arguments

  • $# Number of arguments
  • $@ All arguments, starting from first
  • $1 First argument

Example

#!/bin/bash
function Name() {
   arg1=Argument1;
   arg2=Argument2;
   arg3=Argument3;
   if [ $# -eq 3 ]; then
      arg1=$1;
      arg2=$2;
      arg3=$3;
   fi
   echo "1st argument: $arg1"
   echo "2nd argument: $arg2"
   echo "3nd argument: $arg3"
}
Name $1 $2 $3

To invoke the function use syntax:

Name huu phan www.devopsroles.com

Where

Name: Function Name
huu: Argument #1 passed into the function
phan: Argument #2 passed into the function
www.devopsroles.com: Argument #3 passed into the function

Bash all arguments into a function

#!/bin/bash
function Name() {
   args=("$@")
   echo "Number of arguments: $#"
   echo "1st argument: ${args[0]}"
   echo "2nd argument: ${args[1]}"
   echo "3nd argument: ${args[2]}"
}
Name $1 $2 $3

The screen output terminal:

Bash script arguments into a function

Conclusion

Thought the article, you can use Bash script arguments into a function as above. I hope will this your helpful. More details refer to Bash script.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

Comment moderation is enabled. Your comment may take some time to appear.

This site uses Akismet to reduce spam. Learn how your comment data is processed.