简体   繁体   中英

bash: call function with variables vs function with arguments

Lets take for example next function:

version 1 - with variables:

 backup () {
 for arname in `arname_f`
 do
   slapcat -b "$setnames" -l "$bkdir"/"$ardate"_"$arname".ldif || exit 1
 done
 }

and run it just with code:

 backup;

version 2 - with positional arguments:

 backup () {
 for arname in `arname_f`
 do
   slapcat -b "$1" -l "$2"/"$3"_"$4".ldif || exit 1
 done
 }

and let's run with such code:

 backup $setnames $bkdir $ardate $arname;

Is there any difference in this slants?

The question has nothing to do with Bash as such.

The #1 is the example of "Spaghetti" coding style (global variables) hated by most professionals and simply sane people. It will eventually cause a major problem when someone somewhere changes the parameter and the function starts misbehaving, and you won't have a clue of who/what has changed what where.

The #2 is close to how I would do it. Though, of cause, there may well be a valid reason to prefer #1, it depends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM