Ed Stephenson
Ed Stephenson

Reputation: 774

Bash Script - Store PHP INI location in a variable

I am trying to create a bash script to install various things on my server as I develop. The idea being that it runs on deploy and if I change server, I can just run the script and everything will work.

So far I have this:

#!/bin/sh
apt-get update  # To get the latest package lists
apt-get install imagemagick ghostscript

INI_LOC=echo php -i | grep 'php.ini' | grep 'Loaded Configuration File'

Which is halfway there. $INI_LOC now has the value "Loaded Configuration File => /etc/php/7.1/cli/php.ini"

My question is, how do I change this variable to only show "/etc/php/7.1/cli/php.ini"?

The next step is to then use this variable to add "extension=imagick.so" to the php.ini file, if it hasn't already been added.

Any help would be appreciated.

Upvotes: 0

Views: 562

Answers (2)

Bach Lien
Bach Lien

Reputation: 1060

To get the filename of currently php.ini in use:

INI_LOC=$(php -i|sed -n '/^Loaded Configuration File => /{s:^.*> ::;p;q}')

Then, to check if it has extention=imagick.so:

sed -n 's:^[\t ]*::;/^;/d;/^$/d;s: *= *:=:;/extension="*imagick.so"*/{p;q}' <"$INI_LOC"

If extension=imagick.so not found, then insert it in the [PHP] block while making the backup file with sed -i~

sed -i~ '/^[\t ]*\[PHP\][\t ]*$/{s:$:\nextension=imagick.so:}' "$INI_LOC"

Now, combine all those above:

INI_LOC=$(php -i|sed -n '/^Loaded Configuration File => /{s:^.*> ::;p;q}')
if [ -f "$INI_LOC" ]; then
  FOUND=$(sed -n 's:^[\t ]*::;/^;/d;/^$/d;s:[\t ]*=[\t ]*:=:;/extension="*imagick.so"*/{p;q}' <"$INI_LOC")
  if [ -z "$FOUND" ]; then
    sed -i~ '/^[\t ]*\[PHP\][\t ]*$/{s:$:\nextension=imagick.so:}' "$INI_LOC"
  fi
fi

  1. sed -n '/^Loaded Configuration File => /{s:^.*> ::;p;q}'): find the line containing Loaded Configuration File => at the beginning of that line; print (p) then quit (q)

  2. s:^[\t ]*::;: remove all spaces in the beggining of all lines

  3. /^;/d;/^$/d;: delete (skip) blank lines and commented lines

  4. s:[\t ]*=[\t ]*:=:;: remove all blanks around equal sign

  5. /extension="*imagick.so"*/{p;q}: if extensions=imagick.so or extensions="imagick.so" is found, then print (p) that line and quit (q)

  6. sed -i~ '/^[\t ]*\[PHP\][\t ]*$/{s:$:\nextension=imagick.so:}' "$INI_LOC": insert extension=imagick.so in the [PHP] block

Sorry for my bad English, because I am not an English spoken person.

Upvotes: 1

Tomas
Tomas

Reputation: 59545

$INI_LOC now has the value "Loaded Configuration File => /etc/php/7.1/cli/php.ini"

My question is, how do I change this variable to only show "/etc/php/7.1/cli/php.ini"?

Seems like you just need to remove the "Loaded Configuration File => " string from INI_LOC:

INI_LOC=`echo $INI_LOC | sed 's/Loaded Configuration File => //'`

Upvotes: 1

Related Questions