LoginSignup
0
1

More than 5 years have passed since last update.

文字を中央寄せで表示するスクリプト

Posted at

motdやdotfilesインストールスクリプトのおともにどうぞ。

中央寄せ①

text_center() {
  local columns=$(tput cols)
  local line=
  if [ -p /dev/stdin ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      printf "%*s\n" $(( (${#line} + columns) / 2)) "$line"
    done < /dev/stdin
  else
    line="$@"
    printf "%*s\n" $(( (${#line} + columns) / 2)) "$line"
  fi
}

使い方。

text_center hoge
echo hoge | text_center

中央寄せ②(figlet用)

もっといい書き方がある気はします…。

max_length() {
  local length=
  local max_length=0
  local line=
  if [ -p /dev/stdin ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      length=${#line}
      if [ $length -gt $max_length ]; then
        max_length=$length
      fi
    done < /dev/stdin
    echo $max_length
  else
    line="$@"
    echo ${#line}
  fi
}

with_indent() {
  local length="$1"
  local line=
  local indent=
  local i=
  for ((i=0; i < length; i++)); do
    indent="$indent "
  done
  if [ -p /dev/stdin ]; then
    while IFS= read -r line || [ -n "$line" ]; do
      echo "${indent}${line}"
    done < /dev/stdin
  else
    shift
    line="$@"
    echo "${indent}${#line}"
  fi
}

display_center() {
  local columns=$(tput cols)
  local length=$(echo "$@" | max_length)
  echo "$@" | with_indent "$(((columns - length) / 2))"
}

使い方。

cyan="^[[036m"
default="^[[0m"
echo "${cyan}$(display_center "$(hostname | figlet)")${default}"
0
1
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
0
1