skip to Main Content

I want to get a list of all versions of PHP that have the apache module installed.

This is my function :

availableVersions () {
    available_versions="";

    for php_version in `ls -d /etc/php/*/apache2`
    do
        available_versions="${available_versions}| ${php_version} ";
    done

    echo $available_versions;
}

The return of function is :

| /etc/php/7.0/apache2 | /etc/php/7.1/apache2 | /etc/php/7.2/apache2 | /etc/php/7.3/apache2 | /etc/php/7.4/apache2 | /etc/php/8.0/apache2

But what i want is :

| 7.0 | 7.1 | 7.2 | 7.3 | 7.4 | 8.0

Here is a solution that I have just found, but it will have to be improved.

availablesVersions () {
    available_versions="";

    for php_version in `ls -d /etc/php/*/apache2`
    do
        version="${php_version///etc/''}";
        version="${version///php/''}";
        version="${version///apache2/''}";
        version="${version////''}";

        available_versions="${available_versions}| ${version} ";
    done

    echo $available_versions;
}

Can someone help me?

2

Answers


  1. Something like this maybe.

    #!/usr/bin/env bash
    
    availablesVersions () {
      ##: Just in case there are no files, the glob will not expand to something.
      shopt -s nullglob
    
      ##: Keep variables (array name, varname) local to the function.
      declare -a versions
      local output 
    
      versions=(/etc/php/*/apache2)   ##: Save the files in an array
      versions=("${versions[@]%/*}")  ##: Remove the last /
      versions=("${versions[@]##*/}") ##: Remove the first / longest match
      versions=("${versions[@]/#/ }") ##: Add trailing space
      versions=("${versions[@]/%/ }") ##: Add leading space
      output=$( IFS='|'; printf '|%s' "${versions[*]}" ) ##: Format output
      echo "${output% }" ##: Print the output without the trailing space.
    
      shopt -u nullglob ##: Disable nullglob.
    }
    
    Login or Signup to reply.
  2. Using extglob you can do this:

    (
    shopt -s extglob ## enable extended glob
    versions=(/etc/php/*/apache2) ## Save the files in an array
    IFS='|' ## set IFS to |
    ## print values after replacing unwanted part
    printf '| %s ' "${versions[@]//@(/etc/php/|/apache2)}" 
    )
    

    Output:

    | 7.0 | 7.1 | 7.2 | 7.3 | 7.4 | 8.0
    

    PS: Using ( ... ) to run these commands in a sub-shell to avoid changing IFS for parent shell.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search