Skip to content
Advertisement

Should I be using parameters or export environment variables?

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='john.doe@email.com' && 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 'john.doe@email.com'

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!

Advertisement

Answer

None of your values is optional; I would just use positional parameters.

: ${1?"Requires USER"}
: ${2?"Requires FIRST_NAME"}
: ${3?"Requires LAST_NAME"}
: ${4?"Requires EMAIL"}

sudo -u "$1" git config --global user.name "$2 $3" user.email "$4"

Providing the way for the user to specify values in an arbitrary order is just an unnecessary complication.

You would simply call the script with

setup_git_account.sh 'john' 'John' 'Doe' 'john.doe@email.com'

Reconsider whether the first and last names need to be separate arguments. They are combined into a single argument to git config by the script anyway; just take the name as a single argument as well.

setup_git_account.sh 'john' 'John Doe' 'john.doe@email.com'

(with the appropriate changes to the script as necessary).

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement