Download and insert salt string inside wordpress wp-config.php with Bash

前端 未结 10 2323
有刺的猬
有刺的猬 2021-02-13 06:27

How can I insert the content of the variable $SALT in a specific point (line or string) of a file like wp-contet.php from wordpress using Bash script?



        
10条回答
  •  佛祖请我去吃肉
    2021-02-13 06:50

    Many of the answers rely on the phrase 'put your unique phrase here' being present in the file, so they do not work when you want to change salts after the first time. There are also some that remove the old definitions and append the new ones at the end. While that does work, it's nice to keep the definitions where you would expect them, right after the comment documenting them. My solution addresses those issues.

    I made a few attempts with sed, perl and regex, but there are special characters in the salts and the rest of the config file that tend to mess things up. I ended up using grep to search the document for the unique comment structure that opens and closes the salt definition block, which has the following format:

    /**#@+
     
     */
    
    
    /**#@-*/
    

    Note that if that comment structure is removed or altered, this will no longer work. Here's the script:

    #!/bin/bash -e
    
    # Set Default Settings:
    file='wp-config.php'
    
    # set up temporary files with automatic removal:
    trap "rm -f $file_start $file_end $salt" 0 1 2 3 15
    file_start=$(mktemp) || exit 1
    file_end=$(mktemp) || exit 1
    salt=$(mktemp) || exit 1
    
    function find_line {
    # returns the first line number in the file which contains the text
    # program exits if text is not found
    # $1 : text to search for
    # $2 : file in which to search
    # $3 (optional) : line at which to start the search
    line=$(tail -n +${3:-1} $2 | grep -nm 1 $1 | cut -f1 -d:)
    [ -z "$line" ] && exit 1
    echo $(($line + ${3:-1} - 1))
    }
    
    line=$(find_line "/**#@+" "$file")
    line=$(find_line "\*/" "$file" "$line")
    head -n $line $file > $file_start
    line=$(find_line "/**#@-\*/" "$file" "$line")
    tail -n +$line $file > $file_end
    curl -Ls https://api.wordpress.org/secret-key/1.1/salt/ > $salt
    (cat $file_start $salt; echo; cat $file_end) > $file
    
    exit 0
    

    Strings containing single asterisks, such as "*/" and "/**#@-*/" want to expand to directory lists, so that is why those asterisks are escaped.

提交回复
热议问题