Automatically mount and unmount USB disks using the command line under Gnu/linux

Source: Internet
Author: User

In the command-line environment, it is cumbersome to mount and unmount USB disks by manually typing mount and Umount commands each time. In particular, the Mount command has very many parameters. For example, the partition type of the disk (VFAT, NTFS, etc.), the Mounted directory node, the identity of the user and group to mount (UID and GID), mount after the file and folder permissions (Umask) and so on. So, I wrote two scripts to automatically mount and unmount the USB disk separately. The following are now described separately.

The first is the auto_mount.sh script that loads the USB disk, using it to automatically extract and set the parameters required by the Mount command, execute the Mount command, and check if the mount succeeds:

    • Use the whoami and ID commands to get the uid and GID of the currently logged on user:
user_name=' WhoAmI 'user_id=' id-u $user _name 'user_group_id=' Id-g $user _name '
    • Use the udisks command to obtain the name of the disk partition (volume label) and the type, which is automatically set to disk if the specified partition does not have a volume label:
Vol_label=' udisks--show-info "$" | gawk '/label:.*[[:alnum:]]+/{print tolower ($); exit} 'Vol _type=' udisks--show-info ' | gawk '/type:.*[[:alnum:]]+/{print $; exit} '
    • Call the Mount command to mount the specified disk device to the /media/$vol _label directory with the above parameters. Where umask is set to 002 , the file and folder permissions to be mounted are set to 775 . The Mount command used is as follows, where the parameters are the disk device nodes specified by the auto_mount.sh command line parameter, such as /dev/sdb1 :
sudo mount-t $vol_type"$""/media/$vol _label"uid=$user_id,GID =$user_group_id,umask=002
    • Finally, check to see if the /etc/mtab file contains the directory /media/$vol _label to verify that the mount was successful.

The auto_mount.sh source code is as follows:

#!/bin/Bash# automount a USB diskScript_name="auto_mount.sh"Script_usage=$(Cat<<eofauto_mount.sh [OPTIONS] [DEVICE for DISK]EOF)script_function=$(Cat<<eofautomatically mount a disk to a folder Beneath/media whose name is the volume label of the disk.EOF)Script_doc=$(Cat<<eof-H Display this help.EOF)Script_examples=$(Cat<<eofAUTO_MOUNT.SH/DEV/SDD1EOF)State_prefix="==="Warning_prefix="***"Error_prefix="!!!"functionDisplay_help () {if[-N"$script _usage"]; Then        Echo-E"Usage: $script _usage"    fi    if[-N"$script _function"]; Then        Echo-E"$script _function"    fi    if[-N"$script _doc"] ; Then        Echo-E"\n$script_doc"    fi    if[-N"$script _examples"]; Then        Echo-E"\nexamples"        Echo-E"$script _examples"    fi}# Process Command Options whilegetopts ": H"Opt Do     Case$optinchh) display_helpExit0;;\?) Display_helpExit1;;Esac DoneShift$(($Optind-1))if[ $OSTYPE=' Linux-gnu ']; Then    # The Default volume label If the mounted disk does not has one.    Vol_label_default=diskif[-N"$"]; Then        if[-E"$"]; Then            user_name=' WhoAmI '            user_id=' id-u $user _name '            user_group_id=' id-g $user _name '            Vol_label=' Udisks--show-info ' | gawk '/label:.*[[:alnum:]]+/{print tolower ($); exit} '            Vol_type=' Udisks--show-info ' | gawk '/type:.*[[:alnum:]]+/{print $; exit} '            # Create a directory In/media and chown it into the current user and group            if[-D"/media/$vol _label"]; Then                Echo "$warning _prefix/media/$vol _label already exists!"                if[-N"' Cat/etc/mtab | grep/media/$vol _label ' "]; Then                    Echo "$warning _prefix A device have already been mounted to the path/media/$vol _label!"                    Exit0fi            Else                if[-N"$vol _label"]; Then                    Echo "$state _prefix create/media/$vol _label ..."                Else                    Echo "$warning _prefix The device has no volume label, a default path/media/$vol _label_default would be used!"                    Vol_label=$Vol_label_default                fisudo mkdir"/media/$vol _label"            fi            # Mount the disksudo mount-t $Vol_type "$" "/media/$vol _label"-OUID=$user_id,GID=$user_group_id,umask=002if[-N"' Cat/etc/mtab | grep/media/$vol _label ' "]; Then                Echo "$state _prefix the disk has been successfully mounted to/media/$vol _label!"            Else                Echo "$error _prefix Failed to mount the disk $ to/media/$vol _label!"            fi        Else            Echo "$warning _prefix provide a valid device name!"        fi    Else        Echo "$warning _prefix provide a device name!"    fiElse    Echo "$warning _prefix Operating System or host name is not supported!"fi

Then, run auto_mount.sh as follows to automatically mount the USB disk:

Auto_mount.sh/dev/sdb1

The next auto_umount.sh script to be introduced is very simple. As long as the user specifies the folder that the disk is mounted on, the script checks to see if the folder exists in the /etc/mtab file. If present, call the umount command, and then delete the above folder. Its source code is as follows:

#!/bin/Bash# Auto unmount a diskScript_name="auto_umount.sh"Script_usage=$(Cat<<eofauto_umount.sh [OPTIONS] [mounted PATH of DISK]EOF)script_function=$(Cat<<eofautomatically umount a disk which have been mounted on the specified path.EOF)Script_doc=$(Cat<<eof-H Display this help.EOF)Script_examples=$(Cat<<eofAuto_umount.sh/media/dataEOF)State_prefix="==="Warning_prefix="***"Error_prefix="!!!"functionDisplay_help () {if[-N"$script _usage"]; Then        Echo-E"Usage: $script _usage"    fi    if[-N"$script _function"]; Then        Echo-E"$script _function"    fi    if[-N"$script _doc"] ; Then        Echo-E"\n$script_doc"    fi    if[-N"$script _examples"]; Then        Echo-E"\nexamples"        Echo-E"$script _examples"    fi}# Process Command Options whilegetopts ": H"Opt Do     Case$optinchh) display_helpExit0;;\?) Display_helpExit1;;Esac DoneShift$(($Optind-1))if[ $OSTYPE=' Linux-gnu ']; Then    if[-N"$"]; Then        if[-E"$"]; Then            if[-N"' Cat/etc/mtab | grep ${1%/} ' "]; Thensudo umount"$"sudo rmdir"$"                if[-N"' Cat/etc/mtab | grep ${1%/} ' "]; Then                    Echo "$error _prefix Failed to unmount, the device from the path $1!"                Else                    Echo "$state _prefix Device had been successfully umounted from the path $1!"                fi            Else                Echo "$warning _prefix No device has been mounted to $1!"            fi        Else            Echo "$warning _prefix provide a valid mounted path name!"        fi    Else        Echo "$warning _prefix provide a mounted path name!"    fiElse    Echo "$warning _prefix Operating System or host name is not supported!"fi

Automatically mount and unmount USB disks using the command line under Gnu/linux

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.