1

I have two hard-disks each with Ubuntu, when I access the second hard-disk while being in the first one, the directory has long serial-like name, which does not allow for a quick cd alias.

Which command will allow me to get this name so that I can store a link to it, and put in a variable so that I can use it within my alias? when I open that directory in terminal It looks like:

my_user@my_user:/media/my_user/3d3f80f2-83ee-41f9-9d6e-7145b5fdb7dd1/home/$

but, since this name

3d3f80f2-83ee-41f9-9d6e-7145b5fdb7dd1

changes each time I restart or mount again to that disk, I want instead to be able to do something like:

alias = 'cd /media/my_user/${this_random_long_name}'

I tried to search on how this name is being generated, and how to refer to it formally, but I could not find an answer.

1 Answers1

0

Simple solution

This seems to be an XY problem. Since you only have 2 disks like that, you can get the name of the drive without even knowing it.

See, you are in the first hard drive, so it's mounted at /. Your other hard drive is mounted at /media/my_user/something. Therefore, there is only one directory under /media/my_user. You can use the wildcard * to expand to it:

cd /media/my_user/* # Enter that drive
cd /media/my_user/*/home # Enter a subfolder

To get the "quick cd alias" you wanted:

# Put the following in .bashrc:
alias cdthatdrive='cd /media/my_user/*'
# Then after relogging and opening a new terminal:
cdthatdrive # to use that alias

If you still need the random name:

RANDOM_NAME="$(basename /media/my_user/*)"
alias cdthatdrive="cd /media/my_user/$RANDOM_NAME"

Advanced solution

The simple solution above is preferred if it's sufficient for your use case. Only once you encounter the need for supporting 3 or more drives, you can use a more comprehensive solution:

udisksctl interacts with the daemon that mounts disks on modern Linux. The GUI more or less calls something like udisksctl mount -b /dev/sdb except using DBus. So run udisksctl dump and press / to search for the current random ID the drive is currently mounted at and look for something like /dev/disk/by-id/something-part1 in the "Symlinks:" section above. Then use some DBus stuff to go the other way around:

RANDOM_PATH="/dev/disk/by-id/something-part1" # If your ID is really changing, you can try using wildcard here together with the part (vendor, etc.) that doesn't change
RANDOM_PATH="$(readlink -f "$RANDOM_PATH")"
RANDOM_PATH="$(basename "$RANDOM_PATH")"
RANDOM_PATH="$(dbus-send --system --print-reply=literal --dest=org.freedesktop.UDisks2 /org/freedesktop/UDisks2/block_devices/"$RANDOM_PATH" org.freedesktop.DBus.Properties.Get string:org.freedesktop.UDisks2.Filesystem string:MountPoints)"
RANDOM_PATH="${RANDOM_PATH#*\"}"
RANDOM_PATH="${RANDOM_PATH%\"*}"
# Then you can cd:
cd "$RANDOM_PATH"
Daniel T
  • 5,339