I've always developed my shell scripts using parameters, on a daily-basis or even when developing some automation scripts. However, recently I've tried a different approach, exporting environment variables to my scripts.
#!/bin/bash
: ${USER?"Requires USER"}
: ${FIRST_NAME?"Requires FIRST_NAME"}
: ${LAST_NAME?"Requires LAST_NAME"}
: ${EMAIL?"Requires EMAIL"}
set -x
setup_git_account(){
su - "${USER}" -c "git config --global user.name '${FIRST_NAME} ${LAST_NAME}'"
su - "${USER}" -c "git config --global user.email '${EMAIL}'"
}
setup_git_account
This ensures a smaller code, easy checks if all the required variables are initialized and also, better understanding of what the script is doing, once all the variables are declared on outside.
export USER='john' && export FIRST_NAME='John' && export LAST_NAME='Doe' && export EMAIL='[email protected]' && setup_git_account.sh
Which could be represented like this if implemented with receiving parameters:
setup_git_account.sh --user 'john' --firstname 'John' --lastname 'Doe' --email '[email protected]'
However, the last one, would need way more lines of code to implement the getopts switch case, check the passed parameters values, etc.
Anyway, I know we're used to the second approach, but I think the first approach also has several benefits. And I would like to hear more from you, if there's any downside between the presented approaches. And which one should I be using ?
Thanks!
USER, in particular, is already in use and will be set in your environment already.foo; if you call the first one likefoo=bar utility1, and thenutility1needs to callutility2withoutfoo, thenutility1would need to unsetfoo. Whileutility1can handle its own variables, things get trickier ifutility1doesn't know thatutility2also callsutility3that uses a variablebazalso used byutility1. It would be a nightmare to handle! The current design is much safer as it provides some isolation.findcomes to mind. How would you deal withfind ... \( -sometest -exec utility1 -someoption {} \; \) -o \( -someothertest -exec utility1 -someotheroption {} \; \).