练习:写一个脚本,(使用函数) 1、提示用户输入一个磁盘设备的设备文件,如果设备文件不存在,就提示用户重新输入,直到用户输入正确为止; 当用户给出正确的块设备后: 1、显示用户输入块设备,并提示用户,后续的操作会损坏设备上的所有文件,让用户选择是否继续 2、如果用户输入y,则继续后面的操作; 1、如果用户选择了y, 则抹除指定块设备上的所有分区; 1、在上面的磁盘创建两个主分区: (1) 50M (2) 512M 2、均格式化为ext4文件系统; 3、分别挂载至/mnt/boot和/mnt/sysroot 1、在此设备上安装grub; 2、在/mnt/sysroot目录下创建根文件系统所需要各目录; 1、移植多个应用程序,至少包含bash、ifconfig等; 3、如果用户输入n,则显示用户选择了中止,并退出脚本; 4、输入任何其它字符,则让用户重新选择; 2、用户可以输入quit退出;
#!/bin/bash ######################################################################### # File Name: 007.sh # Author: LookBack # Email: [email protected] # Licence: GNU General Public Licence # Created Time: Wed 23 Jul 2014 04:11:57 AM CST ######################################################################### mntboot="/mnt/boot" mntsysroot="/mnt/sysroot" Program="bash ifconfig ls df ping" checkInput() { clear until [ -n "$(fdisk -l $DiskName)" -a -n "echo $(fdisk -l $DiskName) | grep -o ‘[0-9]‘" ]; do read -p "Plz Enter A Device File Name : " DiskName done } printDisk() { clear fdisk -l $DiskName echo "=============================================================================================" echo "==== ====" echo "==== Subsequent actions will damage all the files on the device, ask whether to continue ====" echo "==== If you continue, please enter: y|Y|Yes|YES|yes|yES|yEs|YeS|yeS ====" echo "==== If you do not want to enter the: n|N|No|NO|no|nO ====" echo "==== ====" echo "=============================================================================================" echo "" read XDisk } makePartition() { dd if=/dev/zero of=$DiskName bs=512 count=1 fdisk $DiskName << EOF n p 1 +50M n p 2 +512M w EOF } mke2fsPartition() { mke2fs -t ext4 ${DiskName}{1,2} } mountPartition() { [ ! -d "$mntboot" ] && mkdir -p "$mntboot" && mount ${DiskName}1 $mntboot [ ! -d "$mntsysroot" ] && mkdir -p $mntsysroot && mount ${DiskName}2 $mntsysroot } installGrub() { grub-install --root-directory=/mnt $DiskName } makeFHSdir() { mkdir {bin,dev,etc,home,lib/modules,lib64,opt,proc,root,sbin,selinux,sys,usr/{bin,sbin,lib,lib64},mnt,media,tmp,var/lib} } transplantProgram() { for I in echo $Program; do [ ! -d ${mntsysroot}$(dirname $I) ] && mkdir -p ${mntsysroot}$(dirname $I) [ ! -f ${mntsysroot}$(which --skip-alias $I) ] && cp $(which --skip-alias $I) ${mntsysroot}$(dirname $I) for II in $(ldd $(which --skip-alias $I) | grep -oE ‘/[^[:space:]]+‘); do [ ! -d ${mntsysroot}$(dirname $II) ] && mkdir -p ${mntsysroot}$(dirname $II) [ ! -f ${mntsysroot}$II ] && cp $II ${mntsysroot}/ done done } nextScript() { printDisk case $XDisk in y|Y|Yes|YES|yes|yES|yEs|YeS|yeS) makePartition mke2fsPartition mountPartition installGrub makeFHSdir n|N|No|NO|no|nO) clear exit 0 ;; *) nextScript esac } read -p "Plz Enter A Device File Name : " DiskName case $DiskName in q|Q|quit|QUIT) clear exit 0 ;; *) checkInput nextScript esac
时间: 2024-10-24 17:13:27