1

Im a bit of a bash novice, so apologies if this is easy Im making a bash script which will run per minute to check that services are up (mysql, redis and so on) per site (we use Glances at the server level)

I would ideally like to have the script be self sufficient, and thus one of those is the ability to read the config file for that site

So, im looking for something like this, but I know this isnt quite right:

FILE=./wp-config.php
if test -f "$FILE"; then
    db_user=`cat wp-config.php | grep DB_USER | cut -d \' -f 4`
    db_password=`cat wp-config.php | grep DB_PASSWORD | cut -d \' -f 4`
fi

FILE=./.env
if test -f "$FILE"; then
    db_user=$(read_var DB_USERNAME .env)
    db_password=$(read_var DB_PASSWORD .env)
fi

Explained in written text:

If ( in this directory a file named wp-config.php exists) // aka a wordpress site

  • Get the DB_USER value
  • Get the DB_PASSWORD value

If ( in this directory a file named .env exists) // aka a laravel site

  • Get the DB_USER value
  • Get the DB_PASSWORD value

The script will then continue to connect to the database and do various things to check and then post that information onto the central monitoring system

Could anyone help me at all get that right, or explain the mistakes What I have there is from extensive googling!!!

Matyhaty
  • 21
  • 1

1 Answers1

0

The Laravel ./env file is in shell script syntax so that part is easy;

. ./.env

The dot before the space before the file name is the shell's instruction to read the file's contents as part of the current script (also called source in some shells, including Bash, but this alias is not portable to POSIX sh, which could be an issue if you need this to run in Jenkins or whatever).

This will obviously add in all the variables from the .env file. If you strictly wanted to read only the two named variables, maybe extract them into a separate file and then source that.

The other file has a useless cat and obsolescent command substitution syntax, and you should not use uppercase for private variables (and probably not reuse the same variable nace, but that's moot now) so I would rewrite that part as

file=./wp-config.php
if test -f "$file"; then
    db_user=$(grep DB_USER "$file" | cut -d \' -f 4)
    db_password=$(grep DB_PASSWORD "$file" | cut -d \' -f 4)
fi

If you put the file name in a variable, use that variable so you only have to change it in one place if you ever need to.

You can always use http://shellcheck.net/ for basic sanity checks, though it would not catch all these issues.

tripleee
  • 175,061
  • 34
  • 275
  • 318