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}"