For example, I’d like to write a bash shell script to do rotating backups with rsync. Should I put it as a standalone script file (backup.sh) or wrap it in a function (backup)? As a script file, I can just run it bash backup.sh. As a function, I can put it in a file such as foo.sh and source it whenever I login, then I can simply run backup as a command to backup my files. The question is, what are the cons and pros for the two strategies?
Or more generally, I am wondering, in what situation, should I implement a functionality as a standalone Shell script file or as a shell function?
Some of my thoughts: I know some graphical sessions (such as KDE, Gnome, etc.) source different files when login. It might cause some confusion if one wants to use the shell functions in a graphically launched applications (such as clicking icon to open emacs). But I prefer to implement as shell functions and pull them together into files, which I think is neat and well organized.
Any other ideas or suggestions?
Use functions for things you’re going to use often. They take up memory and require parsing when the shell starts — parsing which is wasted if you never use the function.
Use scripts for things that take a long time, which you do seldom. The per-invocation parsing time is negligible and the clarity that having the scripts separate brings is beneficial.
So, for backup scripts, I’d strongly recommend a script rather than a function.