1

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?

1
  • We can't know that without seeing your script. You see, the answer how easy it will be to refactor your script mainly depends on its current quality. If all functions are already tightly scoped, not working on global state and such things; it might be easy to move them into a different place. But if everything is tightly tangled bashspaghetti code, than lighthearted attempts for refactoring will break it. Commented Sep 13, 2016 at 17:16

1 Answer 1

3

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 $propfile | cut -d'=' -f2`
  echo $hostname 
}

myscript.sh :
source AllFn.sh
printHost test1
printHost test2
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect example and explanation! Thank you very much! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.