0

I was writing a shell script that wipes, partitions and formats the selected drive when I ran into some trouble with nvme drives.

Essentially what I am trying to accomplish is a way to use the * wildcard in the if statement below to check if the drive is an nvme drive or not so I can then declare variables for the partitions to use later in the script.

This is the relevant part of the script right now:

if [ "$DRIVE" == "/dev/nvme*" ] ; then
    DRIVEp1="${DRIVE}p1"
    DRIVEp2="${DRIVE}p2"
    DRIVEp3="${DRIVE}p3"
else
    DRIVEp1=${DRIVE}1"
    DRIVEp2=${DRIVE}2"
    DRIVEp3=${DRIVE}3"
fi

When I run the script as is and have $DRIVE set to "/dev/nvme0n1", the script ignores the match and goes to the else clause.

0

Assuming you are running bash you have two options for the comparison, either:

if [[ "$DRIVE" =~ "/dev/nvme.*" ]] ; then

or:

if [ "${DRIVE#/dev/nvme}" != "$DRIVE" ] ; then

In the first case, the double brackets allow the extra =~ regular expression match operator; in the second, the DRIVE variable is checked to begin with /dev/nvme by expanding with the leading string /dev/nvme removed to see if the result differs from the full expansion.

With other shells you may need to use an external program, eg:

if [ `echo $DRIVE | grep -o "^/dev/nvme"` == "/dev/nvme" ] ; then
  • Thank you for the detailed answer. I opted for the grep solution, since I'm understand completely what it does. The first solution would have been great, but for some reason it didn't quite work, I'm not entirely sure why. I tried messing about with it but wouldn't return the expected result. The second solution worked but even with your explanation I am unable to fully comprehend what it does. if [ "0n1" != "/dev/nvme0n1"]? Thanks once again. – Daz Apr 29 '17 at 15:28
  • In the first solution, did you notice that the comparison was to "/dev/nvme.*", not "/dev/nvme*"? This is because regular expressions have a slightly different syntax from file name matching, whose ? and * are replaced by . and .*. In the second solution, the advanced parameter expansions are very powerful and well worth learning, but there are few simple guides, though section 4 here is not too bad. Note that here and in most of bash file-matching syntax is used: the =~ operator is a rare exception. – AFH Apr 29 '17 at 16:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.