2

I have the following bash script that expands a volume which outputs a lot of information.

I would like to hide all output from the commands of the script, capture only the size of the volume at the start of the script, then at the end of the script, and output a single line with the change.

The script:

#!/bin/bash

du -h
printf "Fix\nFix\n" |parted ---pretend-input-tty /dev/sda print
parted /dev/sda resizepart 3 100%
pvresize /dev/sda3
lvextend -l +100%FREE /dev/SystemVG/root
xfs_growfs /dev/SystemVG/root
du -h

The du -h command at the start outputs the following:

Filesystem Size Used Avail Use% Mounted on
/dev/mapper/SystemVG-root 12G 6.4G 5.4G 55% /
devtmpfs 858M 0 858M 0% /dev
tmpfs 870M 0 870M 0% /dev/shm
tmpfs 870M 9.4M 860M 2% /run
tmpfs 870M 0 870M 0% /sys/fs/cgroup
/dev/sda2 1.9G 49M 1.8G 3% /boot
/dev/sda1 71M 12M 60M 16% /boot/efi
tmpfs 174M 0 174M 0% /run/user/0

The du -h command at the end outputs the following:

Filesystem Size Used Avail Use% Mounted on
/dev/mapper/SystemVG-root 21G 6.4G 14G 32% /
devtmpfs 858M 0 858M 0% /dev
tmpfs 870M 0 870M 0% /dev/shm
tmpfs 870M 9.4M 860M 2% /run
tmpfs 870M 0 870M 0% /sys/fs/cgroup
/dev/sda2 1.9G 49M 1.8G 3% /boot
/dev/sda1 71M 12M 60M 16% /boot/efi
tmpfs 174M 0 174M 0% /run/user/0

What I'm trying to achieve as output is the following:

[root@system]# ./expandvolume.sh
Volume has been expanded from 12G to 21G.
[root@system]#
jscarle
  • 703
  • 3
  • 12

1 Answers1

2

If you're OK with providing the filesystem name, you could deal the du output like this:

filesystem='SystemVG'
start_du=$(du -h | grep "$filesystem" | awk '{print $2}')

...

end_du=$(du -h | grep "$filesystem" | awk '{print $2}')
echo "Volume has been expanded from $start_du to $end_du"

The intermediate steps to expand the volume just need stdout and/or stderr to be diverted to /dev/null to suppress output, e.g. pvresize /dev/sda3 >/dev/null 2>&1 diverts both (leaving off 2>&1 will still report errors).

Lorccan
  • 667
  • 4
  • 15
  • Is there a way to divert stderr to a variable and use some sort of branching logic: if error echo "Error expanding volume" else echo "Volume expanded"? – jscarle May 15 '20 at 11:10
  • Well, yes, but it might make more sense to abort (the whole script) when an error is encountered (so that you never get to the success message). Here's something on error handling that might give you some ideas: https://linuxhint.com/bash_error_handling/. No doubt someone else will come along with something detailed. – Lorccan May 15 '20 at 11:24
  • commands || { echo "You stepped on a mine!" 1>&2 false } seems to be what I want, just not sure how to use that with multiple commands. – jscarle May 15 '20 at 11:47
  • Found my answer here: https://stackoverflow.com/questions/22009364/is-there-a-try-catch-command-in-bash – jscarle May 15 '20 at 11:52
  • This is what I ended up with as a final script: https://pastebin.com/wQKYJ5Dr – jscarle May 16 '20 at 14:57