Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

standalone shell script vs. shell function?

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?

like image 680
RNA Avatar asked Aug 31 '12 16:08

RNA


2 Answers

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.

like image 185
Jonathan Leffler Avatar answered Nov 15 '22 08:11

Jonathan Leffler


A python-like solution:

#!/bin/bash

caller_shlvl=$1
shift

backup () {
    ...
}

if (( $caller_shlvl < $SHLVL )); then
    backup "$@"
fi

You can do one of two things:

bash script.sh $SHLVL other args

to run the backup when you call the script, or

source script.sh $SHLVL
# Time passes
backup firstarg secondarg etc

which will define the function in the current shell but not execute it.

(Having to pass $SHLVL as the explicit first argument is the closest I could get to simulating Python's

if __name__=="__main__":

It's not pretty, and probably makes this answer not-so-useful.)

like image 37
chepner Avatar answered Nov 15 '22 07:11

chepner