Skip to content

Instantly share code, notes, and snippets.

@andriika
Last active June 19, 2018 04:12
Show Gist options
  • Save andriika/90b2f9d93491eb7937a5ef9e2103c3f6 to your computer and use it in GitHub Desktop.
Save andriika/90b2f9d93491eb7937a5ef9e2103c3f6 to your computer and use it in GitHub Desktop.
collection of common scripting problems and its solutions for both unix bash and windows cmd (batch) platforms

if file not exists

bash:

if [ ! -f .env ]; then
    echo "ERR: .env file not found. Please create one, details: https://devcenter.heroku.com/articles/heroku-local#set-up-your-local-environment-variables"
    exit 1
fi

win:

if not exist .env (
    echo ERR: .env file not found. Please create one, details: https://devcenter.heroku.com/articles/heroku-local#set-up-your-local-environment-variables
    exit /B 1
)

set default value to var (if it's unset)

bash:

AWS_REGION=${AWS_REGION:=us-east-1}
AWS_PROFILE=${AWS_PROFILE:=nonprod}

exit if var is empty

bash:

MONGODB_URI=${MONGODB_URI:?"ERR: required var is empty"}
ARG_1=${1:?"ERR: first argument must be defined"}

win:

if [%MONGODB_URI%] == [] (
    echo MONGODB_URI: ERR: required var is empty
    exit /B 1
)

get dir's absolute path by relative (dir must exists)

bash:

SOURCE=relative/path/to/dir
SOURCE=$(cd $SOURCE && pwd)

set vars defined in separate file

Given variables defined in the .env file like:

MONGODB_URI=mongodb://user:pass@host:port/db
FOO=BAR

We can assign (evaluate) those vars and use them as a standard script vars

bash:

source .env
echo ${MONGODB_URI}

win:

for /F "tokens=*" %%A in (.env) do SET %%A
echo %MONGODB_URI%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment