Marc Le Bihan
Marc Le Bihan

Reputation: 3304

Parse a part of the result of a bash command to store it into a variable

My question is really a bash question even if it talks about mounting a disk.

During the creation of a VM, by a script, I mount this disk:

sudo mount -t ext4 /dev/sdb /data

And I would like to keep it every time my system start. Make this mount become automatic. I learnt that I had to edit the /etc/fstab file for that : append a line on it.

When my disk is mounted, I have to run a command:

$ sudo blkid /dev/sdb
/dev/sdb: UUID="238d1293-918e-42e1-a081-a41f497636d0" TYPE="ext4"

To get the UUID I need to mention in the line I append on my /etc/fstab file:

UUID=238d1293-918e-42e1-a081-a41f497636d0       /data      ext4    defaults      0       0

My question is: May I parse by bash the result of the blkid command, catch the part UUID="238d1293-918e-42e1-a081-a41f497636d0" from the /dev/sdb: UUID="238d1293-918e-42e1-a081-a41f497636d0" TYPE="ext4" content and store it into a variable?

Upvotes: 2

Views: 581

Answers (3)

Charles Duffy
Charles Duffy

Reputation: 295403

Bash's built-in regex support is suited to task. In the below function, we're testing the output of blkid against the regex UUID="([^"]+)", and emitting the match group contents (everything inside the parenthesis) if a match is found:

uuid_for_device() {
  local uuid_re blkid_text      # Declare our locals so we don't leak into global scope
  uuid_re='UUID="([^"]+)"'      # Save the regex to a variable; less gotchas this way
  blkid_text=$(sudo blkid "$1") || return # Collect the data we're going to match against
  [[ $blkid_text =~ $uuid_re ]] && echo "${BASH_REMATCH[1]}" # Emit output if regex matches
}

...will emit your desired UUID given uuid_for_device /dev/sda, which you can capture into a variable as usual (sda_uuid=$(uuid_for_device /dev/sda)).


That said, for your real-world use case, you're better off just using a more appropriate tool for the job:

uuid_for_device() { findmnt -n -o UUID "$1"; }

sda_uuid=$(uuid_for_device /dev/sda)

Or, of course, simply:

sda_uuid=$(findmnt -n -o UUID /dev/sda)

Upvotes: 2

DumbNewbie
DumbNewbie

Reputation: 160

Use sed:

YOUR_COMMAND | sed -e 's/.*UUID="\([0-9a-f-]*\)".*/\1/'

You can use backticks for example to store it:

a=`YOUR_COMMAND | sed -e 's/.*UUID="\([0-9a-f-]*\)".*/\1/'`

echo $a

Upvotes: 1

choroba
choroba

Reputation: 241868

Use parameter substitution:

uuid=$(sudo blkid /dev/sdb)
uuid=${uuid#*UUID=\"}  # Remove from left up to UUID="
uuid=${uuid%%\"*}      # Remove from right from the leftmost "
echo "$uuid"

Upvotes: 3

Related Questions