I am writing a shell script (meant to work with Ubuntu only) that assumes that a disk has been previously open (using the command below) to make operations on it (resize2fs, lvcreate, ...). However, this might not always be the case, and when the disk is closed, the user of the script has to run this line before running the script, asking for his/her passphrase:
sudo cryptsetup luksOpen /dev/sdaX sdaX_crypt
Ideally, the script should start with this command, simplifying the user sequence. However, if the disk was indeed already opened, the script will fail because an encrypted disk cannot be opened twice.
How can I check if the disk was previously open? Is checking that /dev/mapper/sdX_crypt exists a valid solution / enough? If not or not possible, is there a way to make the command run only if necessary?
You can use the lsblk command.
If the disk is already unlocked, it will display two lines: the device and the mapped device, where the mapped device should be of type crypt.
# lsblk -l -n /dev/sdaX
sdaX 253:11 0 2G 0 part
sdaX_crypt (dm-6) 253:11 0 2G 0 crypt
If the disk is not yet unlocked, it will only show the device.
# lsblk -l -n /dev/sdaX
sdaX 253:11 0 2G 0 part
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With