Bash functions
functions in bash used to perform repetitive tasks , we can put all task or command in one function and we can used it by just calling function name.
Creating Functions
syntax
functionName () {
list of commands
}
#!/bin/sh DisplayMe() { echo "Hello all" } # using function name DisplayMe
Output
Hello all
Bash function arguments
#!/bin/sh DisplayMe () { echo "Hi $1 $2" } DisplayMe ken corner
Output
Hi ken corner
Returning Values from Functions
#!/bin/sh DisplayMe () { echo "Hi $1 $2" return 55 } DisplayMe Ken corner # Capture value returns by last command returnValue=$? echo "Function return value is $returnValue"
Output
Hi ken corner Function return value is 55
Nested Functions
Nested function is function within function
Example
#!/bin/sh # Calling one function from another FunctionOne () { echo -e "I am in Function One\n" FunctionTwo } FunctionTwo () { echo "I am in Function Two" } # Calling FunctionOne. FunctionOne
Output
I am in Function One I am in Function Two
Explanation : in the above example we can see that we only called FunctionOne and then FunctionOne called to FunctionTwo
Bonus Example script of function in bash
In below script we have created some function to get the Total size of RAM, CPU details ,Total core of CPU and Ubuntu Server version, we are using case for menu selection.
Note: In case *) is for value which is not match in case value.
#!/bin/sh GetRamSize() { TotalRam=$(free -m | grep 'Mem:*' | awk '{print $2}') echo " Total RAM size is : $TotalRam MB" } GetCPUDetail() { CpuDetailsTMP=$(cat /proc/cpuinfo | grep 'model name' | uniq | awk '{print $4$5$6$7}') CpuDetailsNew=$(echo $CpuDetailsTMP | sed -e 's/\//-/g') CpuDetails=$(echo $CpuDetailsNew | tr -d ' ') echo "CPU is : $CpuDetails" } NoOfCoreinCPU() { CpuCore=$(grep -c ^processor /proc/cpuinfo) echo "Total No. of Core in CPU : $CpuCore" } UbuntuServerVersion() { ServerVersion=$(lsb_release -r --short) echo "Ubuntu Server Version : $ServerVersion" } echo " Please Select: 1. Display RAM Size 2. Display CPU detail 3. Display Total Core in CPU 4. Display Version of Ubuntu Server " echo "Please Enter Number: " read GetValue case $GetValue in 1) GetRamSize ;; 2) GetCPUDetail ;; 3) NoOfCoreinCPU ;; 4) UbuntuServerVersion ;; *) echo "Sorry you have enter wrong number" ;; esac
You May Also Enjoy Reading This …
Bash Script Course
Bash script or Shell script