user2966991 user2966991 - 2 months ago 8
Linux Question

Outsourcing bash shell script functions

I have a very big shell script written in bash and want to outsource some functions to an extra file, because I have the same functions in some other scripts.

So I could outsource them, fix / improve them once and reuse it in multiple main scripts.

Can I just "copy and paste" these functions from the current big script to single smaller ones and include them later in the big script using

source functions_versionCheck.sh
?

Answer

Yes absolutely. I work on big shell script automation framework and it based on this same idea. Here is one basic example :

AllFn.sh :

function echoBold(){
echo "******************************************"
echo "$1"
echo "******************************************"
}

myscript.sh :

source AllFn.sh
echoBold "This is a bold message"

Just you have to make the AllFn.sh script as generic as possible and make it read the properties from some property file so that you can customize the generic function for specific parameter you pass. e.g.

properties.txt:
test1_host=hostname1
test2_host=hostname2

AllFn.sh :
propfile=/home/$USER/properties.txt
function printHost(){
  hostname=`grep ${1}_host | cut -d'=' -f2`
  echo $hostname 
}

myscript.sh :
source AllFn.sh
printHost test1
printHost test2
Comments