Script To Find SCSI Bus Id

Despite Linus’ assertion that the concept of SCSI Ids is "f*cking idiotic", sometimes they’re necessary. For example, sometimes the following will work to recover an Offlined device:

echo "scsi remove-single-device 99 0 3 0" > /proc/scsi/scsi
echo "scsi add-single-device 99 0 3 0" > /proc/scsi/scsi

There’s a script named lsscsi that’ll output the ids and device names for you, but it doesn’t give you the id in a format that’s easy to consume in your own scripts. Further, it only prints the real device name, not the symlinked alternatives. So, I cooked up a bash script that takes the device name of a scsi device, resolves it to the real device name if it’s a symlink, and then outputs the SCSI Id in a format usable for the above use case. Naturally, you’ll need to make sure that lsscsi is installed; for ubuntu users, apt-get will do the trick.

#!/bin/bash

function parse_lsscsi {
    {
        while read line
        do
            echo "$line" | grep "$1" | sed "s%\[\([0-9]*\):\([0-9]*\):\([0-9]*\):\([0-9]*\).*$1%\1 \2 \3 \4%"
        done
    } | tee
}

function resolve_device_name {
	dev=$(readlink $1)
	[ $? == 1 ] && echo $1 && return 0
	echo /dev/$dev
}
dev=$(resolve_device_name $1)
lsscsi 2>&1 | parse_lsscsi $dev

Example usage and output:

prompt> ./scsi_id /dev/powerfilecd2
98 0 2 0
prompt> ./scsi_id /dev/sr2
98 0 2 0