我正在创建 bash 脚本,该脚本给出 mysql innodb 日志文件的大小MB。目前我正在获取其以字节为单位的输出。请查看以下脚本并帮助获取以 MB 为单位的输出。
#! /bin/sh
a=$(mysql -uroot -proot -e "SHOW VARIABLES" | grep innodb_log_file_size | cut -f2)
b=$(echo "$a/$10240" )
echo {"Innodb_log_file_size":"'$b'"' }
答案1
在 bash 中你可以做这样的事情。
您可以使用(( ))
来强制执行算术语境。
当谈到你有的尺寸时MB vs MiB,参见右侧图表。
#!/bin/bash
psize()
{
local name="$1"
local -i val="$2";
local u=""
case "$3" in
"B") u="B" ;;
"K") u="KiB"; ((val /= 1024 ));;
"G") u="GiB"; ((val /= 1024 * 1024 * 1024 ));;
# Defaults to MiB
*) u="MiB"; ((val /= 1024 * 1024 ));;
esac
printf "%-22s: %d %s\n" "$name" "$val" "$u"
}
unit=""
# Check if wanted size is given by user
if [[ "$1" =~ ^(B|K|M|G)$ ]]; then
unit="$1"
fi
# Use tab as delimiter and read into variables "name" and "value"
while IFS=$'\t' read -r name value; do
case "$name" in
"innodb_log_file_size"|"innodb_log_buffer_size")
psize "$name" "$value" "$unit"
;;
esac
done < <(mysql -uroot -ppass -e "SHOW VARIABLES")
用 grep
如果你想混合 grep 等:
psize()
{
local -i a=$(mysql -uroot -ppass -e "SHOW VARIABLES" | \
grep innodb_log_file_size | cut -f2)
local -i b=0;
local u=""
case "$1" in
"B") u="B" ; b="$a";;
"K") u="KiB"; ((b = a / 1024 ));;
"G") u="GiB"; ((b = a / 1024 / 1024 / 1024 ));;
*) u="MiB"; ((b = a / 1024 / 1024 ));;
esac
printf "Innodb_log_file_size: %d %s\n" "$b" "$u"
}
unit="M"
if [[ "$1" =~ ^(B|K|M|G)$ ]]; then
unit="$1"
fi
psize "$unit"
您可以通过以下方式使用:
./myscript # Defaults to MiB
./myscript B # Print in bytes
./myscript G # Print in GiB
...
供参考。
使用 awk:
psize()
{
awk -v unit="$1" '
BEGIN {
if (unit == "")
unit="M"
switch (unit) {
case "B":
ratio = 1;
break;
case "K":
ratio = 1024;
break;
case "G":
ratio = 1024 * 1024 * 1024;
break;
default:
ratio = 1024 * 1024;
break;
}
if (unit != "B")
unit = unit "iB"
}
/^innodb_log_file_size\s/ {
printf("Log size : %d %s\n", $2 / ratio, unit);
}
/^innodb_log_buffer_size\s/ {
printf("Buffer size: %d %s\n", $2 / ratio, unit);
}
' <(mysql -uroot -e "SHOW VARIABLES" -ppass)
}
psize "$unit"