LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fdisk -l output with partition label appended - Bash script available (https://www.linuxquestions.org/questions/programming-9/fdisk-l-output-with-partition-label-appended-bash-script-available-452904/)

Emmanuel_uk 06-08-2006 01:40 PM

fdisk -l output with partition label appended - Bash script available
 
This ugly bash script does it. Feel free to improve. Could become a function or alias.
I could never remember which partition was what.

Code:

#!/bin/bash
#Append partition name to fdisk -l output
#Version 0.0a
#By Emmanuel_uk and whoever wants
#Not tested with anything but ext3 for now. Fat ignored by e2label indeed
#Need root privelege or at least sudo fdisk
# Ugly formating with --------->  Example
#Device Boot      Start        End      Blocks  Id  System
#/dev/sda2            765        1528    6136830  83  Linux ------------>LabelName

#Storing a normal output (wherever we are - ugly)
fdisk -l > monfdisk.txt

echo "------------------------"
#Opening and looping around fdisk output
exec 3<> monfdisk.txt
while read line <&3
do {
 # echo "$line" | grep '/dev/' | awk '{print $1}' | grep '/dev/'
  #Parsing each line, we do no want a glob *, we want dev, the first field only,
  #and /dev/ again because it needs to be first in the line
  resu=`echo "$line" | grep --invert-match '*' | grep '/dev/' | awk '{print $1}' | grep '/dev/' `
  nb_char=${#resu}  #strings syntax to know how many characters were matched in one line
  #echo $resu
  #echo "here  "$nb_char
  if [ $nb_char -gt 4 ]; then #we found /dev
  echo "$line"" ------------>"`e2label $resu 2>/dev/null`; #error by e2label into null oblition
  else
  #just a normal line to print
  echo "$line"  # Quote needed otherwise a *, like that of the geometry is seen as a glob
  fi
  (( Lines++ ));  #Keep this. Beautiful syntax             
}
done
exec 3>&-
echo "Number of lines read = $Lines"   

exit 0


unSpawn 06-08-2006 03:25 PM

fdisk -l > monfdisk.txt
Ah, you mean like "ln -sf /etc/shadow ./monfdisk.txt"? Better use mktemp.And you don't really need a tempfile and [ $nb_char -gt 4 ] seems a bit too generic a test to me, maybe make it "expr match string regex" or just test:
fdisk -l|while read l; do l=(${l}); [ "${l[0]:0:5}" = "/dev/" ]

`e2label $resu 2>/dev/null`
I am allergic to backticks as it makes for bad readability, but that's my personal gripe I guess. What you *could* do is make errors work for you by using var=$(e2label $resu 2>/dev/null) and echo "${var:=No label found}"


This ugly bash script does it.
Hmm. For me it doesn't (fdisk v2.11y), but why not just:
Code:

fdisk -l|grep /dev/[s,h]d..*83..*Linux$|awk '{print $1}'|\
while read p; do echo "${p}: $(e2label $p)"; done

? Or am I missing something vital here?

Emmanuel_uk 06-08-2006 03:54 PM

thanks a lot for the suggestions (Still learning)

# fdisk -v fdisk v2.12a
I wonder what changed between version (formating?)

Quote:

# ./myfdisk.sh
------------------------

Disk /dev/hda: 82.3 GB, 82348277760 bytes
255 heads, 63 sectors/track, 10011 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda1 * 1 509 4088511 83 Linux
/dev/hda2 510 10011 76324815 5 Extended ------------>
/dev/hda5 510 1146 5116671 83 Linux ------------>slack10p1
/dev/hda6 2516 3279 6136798+ 83 Linux ------------>mainOS_mandy10p2
/dev/hda7 3280 3342 506016 82 Linux swap ------------>
/dev/hda8 3343 10011 53568711 83 Linux ------------>mainHomeHDA8
...
Device Boot Start End Blocks Id System
/dev/sdb1 * 1 764 6136798+ 83 Linux
/dev/sdb2 765 1528 6136830 83 Linux ------------>
/dev/sdb3 1529 2292 6136830 83 Linux ------------>
/dev/sdb4 2293 19457 137877862+ 5 Extended ------------>
Quote:

fdisk -l > monfdisk.txt
Yes, an ugly temp file this is. Will try a way round it.

but why not just:
Code:

disk -l|grep /dev/[s,h]d..*83..*Linux$|awk '{print $1}'|\
while read p; do echo "${p}: $(e2label $p)"; done

1) no because it does not deal with errors (like no label)
2) I want the rest of fdisk -l intact
3) I see your point, one can get inspired from your example

>>Or am I missing something vital here?
Yes, I am just a hobbyist ;)
I want the rest of fdisk -l intact

With the above code, result is
Quote:

/dev/sda1: vector5p1_SDA1
e2label: Bad magic number in super-block while trying to open /dev/sda2
Couldn't find valid filesystem superblock.
/dev/sda2:
e2label: Bad magic number in super-block while trying to open /dev/sda3
Couldn't find valid filesystem superblock.
/dev/sda3:

unSpawn 06-08-2006 07:29 PM

I wonder what changed between version
Prolly nothing much I can see. Anyway. Here's some "sh -x myfdisk.sh" output of two partitions:
Code:

+ read line
++ echo '/dev/hda10        1248      1370    987966  83  Linux'
++ grep --invert-match '*'
++ grep /dev/
++ awk '{print $1}'
++ grep /dev/
+ resu=/dev/hda10
+ nb_char=10
+ '[' 10 -gt 4 ']'
++ e2label /dev/hda10
+ echo '/dev/hda10        1248      1370    987966  83  Linux ------------>'
/dev/hda10        1248      1370    987966  83  Linux ------------>
+ ((  Lines++  ))
+ read line
++ echo '/dev/hda11        1371      1605  1887603  83  Linux'
++ grep --invert-match '*'
++ grep /dev/
++ awk '{print $1}'
++ grep /dev/
+ resu=/dev/hda11
+ nb_char=10
+ '[' 10 -gt 4 ']'
++ e2label /dev/hda11
+ echo '/dev/hda11        1371      1605  1887603  83  Linux ------------>'
/dev/hda11        1371      1605  1887603  83  Linux ------------>
+ ((  Lines++  ))

Now if I type "/sbin/e2label /dev/hda10" the result is "/home" and for 11 it's "/opt".


Yes, an ugly temp file this is. Will try a way round it.
Well, if you want to avoid using mktemp, then maybe
tempf=$(date|sha1sum); tempf=${tempf:0:30}; tempf="${TMPDIR:=$HOME}/myfdisk.$tempf"


With the above code, result is
Maybe the regex should read "/dev/[s,h]d.*[[:blank:]]83[[:blank:]].*Linux$", but I'm pretty sure the type 83 should exclude "empty" containers. Hmm.


BTW, got yourself a copy of the ABS or "Advanced Bash Scripting" guide? Has some helpful stuff.

Emmanuel_uk 06-09-2006 02:18 AM

Code:

+ '[' 10 -gt 4 ']'
++ e2label /dev/hda10
+ echo '/dev/hda10        1248      1370    987966  83  Linux ------------>'

it suggests e2label /dev/hda10 is not returning anything (or just an error)

The guilty code line is
echo "$line"" ------------>"`e2label $resu 2>/dev/null`
Quote:

Now if I type "/sbin/e2label /dev/hda10" the result is "/home" and for 11 it's "/opt".
So is this a bash version issue, a backtick issue, or just
that e2label is not in the path?

Ta, I have the advanced bash available. This is only my third bash script,
so I really struggle with remembering syntax or being inventive.

I will try to improve with your latest suggestion,
and with a ^/dev/ regexp and a sed -i that should work
(it is piping with sed that always trouble me, I tried early on but failed)

unSpawn 06-09-2006 05:45 AM

So is this a bash version issue, a backtick issue, or just that e2label is not in the path?
No, none of that. My fault was I, ahhh "customised", tempfile usage w/o noticing later on. Works as advertised.

Emmanuel_uk 06-09-2006 04:01 PM

Improved script - no temp file. Reiserfs included. Better coding
 
Et voila. Less ugly. It does the job I wanted.
Can be improved as needed. Cannot make it a one liner, sorry...

Output example
Code:

/dev/hdb3          10641      11659    8185117+  83  Linux --------> suse
/dev/hdb5            1785        5608    30716248+  7  HPFS/NTFS
/dev/hdb6            5609        6627    8185086  83  Linux --------> mainOS_mandy10p2
/dev/hdb7            6628        6689      497983+  82  Linux swap
/dev/hdb8            6690        6816    1020096  82  Linux swap

Code:

#!/bin/bash
#Append partition label/name to fdisk -l output
#Version 0.01b  By Emmanuel_uk using unSpawn kind suggestions
#Tested with ext3 and Reiserfs. Fat ignored.
#Need root privelege or at least sudo fdisk

#Output will be like
#Device Boot      Start        End      Blocks  Id  System
#/dev/sda2            765        1528    6136830  83  Linux --------> somelabel

separator=" --------> " #Appended before partition label. Spaces are good
msg_if_nolabel="no_label_found"
verbose=1 #1 for on, 0 otherwise

#Sanity check reiserutil=1 if reiserfstune is present (used to catch partition name)
reiserutil=$(which reiserfstune)  #path + length is > = 12 characters
if [ ${#reiserutil} -ge 12 ]; then reiserutil=1; else reiserutil=0; fi  #1=present
# No warning here if reiserfstune not there. We want to keep fdisk output as close as normal

fdisk -l | while read line;  #looping around fdisk -l output
do {  #Parsing each line, we want a line starting with /dev/, Linux type but not swap, the first field only
  aHDdevice=$(echo "$line" | grep '^/dev/' | grep -i 'Linux' | grep -iv 'swap'| awk '{print $1}'  )
  if [ "${aHDdevice:0:5}" = "/dev/" ]; then #we found a device
  thelabel=$( e2label $aHDdevice 2>/dev/null ) #error by e2label into null oblition
  #If zero length label and reiserfstune available query further
  if [ ${#thelabel} -eq 0 ] && [ $reiserutil -eq 1 ]; then #empty label or no label. Test if reiserfs then
    thelabel=$( reiserfstune $aHDdevice 2>/dev/null | grep LABEL | awk '{print $2}' )
    if [ ${#thelabel} -eq 0 ]; then thelabel=$msg_if_nolabel; fi
  fi #fi of reiserfs or ext2/ext3
  echo "$line"$separator"$thelabel"; #modified fdisk -l output
  else    #just a normal fdisk output line to print unchanged
  echo "$line"  # Quote needed otherwise a * is a glob, like that of the geometry
  fi
}
done
if [ $reiserutil -eq 0 ] && [ $verbose -eq 1 ]; then
 echo "Note: reiserfstune not present. Partition labels for Reiserfs ignored";
fi
exit 0


unSpawn 06-10-2006 05:08 AM

Dunno if it qualifies, you determine yourself, but maybe it's something to add a pointer to in the Tips 'n tricks thread.


All times are GMT -5. The time now is 04:38 PM.