LoginSignup
2
2

More than 5 years have passed since last update.

canonicalとalternateを挿入するシェルスクリプト

Last updated at Posted at 2015-07-20

URL正規化タグを挿入するシェルスクリプト

スマホ用テンプレート(_sp.html)とPC用テンプレート(.html)を別途で作成していて
URL正規化タグをいれるの忘れた時にチカラを発揮します。

特徴

  • titleタグのすぐ下に挿入されます。
  • 相対パスで記述されます。
  • バックアップをとっているか聞いてきます。(聞いてくるだけでバックアップはしません)
  • ブレイクポイント(media screen)を対話型で指定できます。defaultはmedia=only screen and (max-width: 787px)です。

使い方

  1. 対象のディレクトリにurl_ca.shファイルを保存してください。
  2. ターミナルを起動
  3. $ cd で対象ディレクトリに移動
  4. $ ./url_ca.shで実行

-bashエラーになる時は、
chmod u+x ./url_ca.sh
などをして、実行権限を自身に付与してから再度./url_ca.shを実行してみてください。

シェルスクリプト

url_ca.sh
#!/bin/bash
# このファイルを対象フォルダにコピーしてターミナルから実行すると
# *_sp.htmlにはcanonicalが
# *.htmlにはalternateが入ります
COLOR_Y="\033[0;33m"
COLOR_R="\033[0;31m"
COLOR_M="\033[0;35m"
COLOR_OFF="\033[0;m"
LF=$(printf '\\\012_')
LF=${LF%_}
echo -e "${COLOR_M}Hi! it will continue to insert text 'canonical' or 'alternate' in htmls for SEO."
echo -e "Already backed up were taken?${COLOR_OFF} [yes/no]"
read backupYes
case `echo $backupYes | tr y Y` in "" | Y*)
        echo -n -e "${COLOR_Y}OK! and Please enter breakpoint px. default [787]  ${COLOR_OFF}"
        read brakePoint
        defaultBP=787
        if [[ "$brakePoint" = "" ]]; then
            brakePoint=$defaultBP
        fi
        echo -e "${COLOR_Y}OK!! let's run sh!!!!${COLOR_OFF}"

        pchtmls="*[^_sp].html"
        sphtmls="*_sp.html"

        for convertSP in ${sphtmls}
        do
            fileNamePC=${convertSP/_sp./.}
            title="</title>"
            canonical="</title>$LF<link rel=\"canonical\" href=\"$fileNamePC\" >"
            sed -i "" -e "s:$title:$canonical:" ${convertSP}
            echo -e "$convertSP ${COLOR_Y}FINISH!${COLOR_OFF}"
        done

        for convertPC in ${pchtmls}
        do
            mScreen="(max-width\: ${brakePoint}px)"
            fileRenameSP=${convertPC/./_sp.}
            title="</title>"
            alternate="</title>$LF<link rel=\"alternate\" media=\"only screen and $mScreen\" href=\"$fileRenameSP\" >"
            sed -i "" -e "s:$title:$alternate:" ${convertPC}
            echo -e "$convertPC ${COLOR_Y}FINISH!${COLOR_OFF}"
        done
    ;;
        *) echo -e "${COLOR_R}Oops!! Do backup now hurry up!!${COLOR_OFF}";;
esac
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2