In bash you could do something like this.
You can use (( ))
to enforce an arithmetic context.
When it comes to sizes you have MB vs MiB, see chart on right hand side.
#!/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")
With grep
If you want to mix in grep etc.:
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"
Which you could use by:
./myscript # Defaults to MiB
./myscript B # Print in bytes
./myscript G # Print in GiB
...
For ref.
Using 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"
du -sh /var/lib/mysql/ib_logfile*
– Rahul Patil Apr 9 at 6:31