Table of Contents
shell代码片段收集
获取磁盘大小
# Return the size of the drive in MB get_drive_size () { ldrive=$1 # Make sure you can print disk info using parted parted --script /dev/$ldrive print >/dev/null 2>&1 # If unable to read disk, it's likely it needs a disklabel if [ "$?" != "0" ]; then echo "Creating a new disklabel on $ldrive" >> $INSTALL_LOG echo "parted /dev/$ldrive mklabel msdos" >> $INSTALL_LOG output=$(parted -s /dev/$ldrive mklabel msdos) # Get the drive size from parted lsize=$(parted -s /dev/$ldrive p | grep "^Disk" | awk '{ print $3 }') if [ $(echo $lsize | grep error) ]; then echo "Unable to read disk label. Exiting." exit 1 fi fi # Get the drive size from parted lsize=$(parted -s /dev/$ldrive p | grep "^Disk" | awk '{ print $3 }') # Get the reported units (mB, GB, kB) lmodifier=$(echo $lsize | sed 's/[0-9\.]//g') # remove the modifier lsize=$(echo $lsize | sed 's/[a-z,A-Z]//g') # Remove any fractions lsize=$(echo $lsize | cut -f1 -d'.') # Translate our size into mB if not there already if [ $lmodifier = "GB" ]; then lsize=$(($lsize * 1000)) elif [ $lmodifier = "kB" ]; then lsize=$(($lsize / 1000)) fi echo $lsize }disk_size=`fdisk -l $CF | grep MB | cut -d”:” -f2 | cut -d “,” -f1| sed s/MB//g `
变为大写
upper_str() { upper=`echo $1 | tr "[a-z]" "[A-Z]"` echo $upper }
判断返回值
echo $TOS_VERSION | grep "^3.3.016" if [ $? != 0 ] then VERSION_016="false" else VERSION_016="true" fi
提问
auto_echo "Are you sure to begin[y/n]:" while read answer do answer=`upper_str $answer` if [ "$answer" = "Y" ] then break elif [ "$answer" = "N" ] then write_free exit fi auto_echo "Are you sure to begin[y/n]:" done
for循环
for x in /var/log/* do echo `basename $x` is a file living in /var/log done
while and until
myvar=0 while [ $myvar -ne 10 ] do echo $myvar myvar=$(( $myvar + 1 )) done myvar=0 until [ $myvar -eq 10 ] do echo $myvar myvar=$(( $myvar + 1 )) done
case
*$x为文件名,只获取文件的后缀,至于是为什么现在不明白? *
case "${x##*.}" in gz) gzunpack ${SROOT}/${x} ;; bz2) bz2unpack ${SROOT}/${x} ;; *) echo "Archive format not recognized." exit ;; esac
读取文件
#! /bin/bash while read LINE do echo $LINE done < /etc/passwd
awk按域搜索的例子
while read line; do cp aaaa $line; done << (awk '{for(i=1; i <= NF; ++i){if($i ~/^-l/){gsub("^-l","lib",$i); printf("%s.so\n", $i)}}}' libso.txt | sort -u)