红联Linux门户
Linux帮助

linux查看目录的剩余可用空间【shell脚本】

发布时间:2017-08-24 16:17:57来源:blog.csdn.net/u010317005作者:oba没有马
Linux中暂时没发现现成的命令,因此可用用shell脚本结合df -h命令来实现
 
实现思路:
1、输入一个路径
2、获得df -h信息
3、保存根目录的可用空间大小
4、除了跟根目录之外的其他挂载目录匹配路径,如果匹配成功,取该路径的可用空间,或者取根目录的可用空间
 
shell脚本:
#!/bin/bash
#########################################
#author:
#    yxj
# BLOG:
#    http://blog.csdn.net/u010317005
#usage:
#  ./get_dir_avail_space [dir]
#e.g:
#   ./get_dir_avail_space /root
#   ./get_dir_avail_space 
#########################################
############get test path###############
if [ -z $1 ];then
 read -p "input the path(e.g: /root):" path
else
 path=$1
fi
if [ "${path:0:1}" = "/" ];then 
  if [ ! -d ${path} ];then
   # echo "create new path:${path}"
    mkdir -p ${path}
  fi
 # echo "absolute directory:${path}"
else
  pwd=`pwd`
  if [ ! -d "${pwd}/${path}" ];then
  # echo "create new path:${pwd}/${path}"
   mkdir -p ${pwd}/${path}
  fi
  path=${pwd}/${path}
 # echo "path:${path}"
fi
##########get data from df -h#############
df -h | while read line
do 
  #for var in $line
  line_path=`echo ${line} | awk -F' ' '{print $6}'`
  line_avail=`echo ${line} | awk -F' ' '{print $4}'`
   if [ "${line_path:0:1}" != "/" ]; then 
     continue
   fi
   if [ "${line_path}" = "/" ]; then
      root_avail=${line_avail}
     #echo "root_avail:${root_avail}"
     if [ -f /tmp/tmp_root_avail ];then 
       rm /tmp/tmp_root_avail
     fi
     echo ${root_avail} > /tmp/tmp_root_avail
     continue
   fi
  path_length=${#line_path}
  if [ "${path:0:${path_length}}" = "${line_path}" ];then
   # echo "${path} contain path:${line_path}" 
    path_avail=${line_avail}
    if [ -f /tmp/tmp_path_avail ];then
      rm /tmp/tmp_path_avail
    fi
    echo ${path_avail} > /tmp/tmp_path_avail
    break
  fi
done
#############get data from temp file###############
if [ -f /tmp/tmp_path_avail ];then
 path_avail=`cat /tmp/tmp_path_avail`
 rm /tmp/tmp_path_avail
fi
if [ -f /tmp/tmp_root_avail ];then
 root_avail=`cat /tmp/tmp_root_avail`
 rm /tmp/tmp_root_avail
fi
###################compute######################
if [ -z ${path_avail} ];then
#   echo "root_avail:${root_avail}"
#   echo "path_avail=${path_avail}"
   path_avail=${root_avail}
fi
 
echo "${path_avail}"
 
保存为get_dir_avail_path.sh
chmod 777 get_dir_avail_path.sh修改权限
#usage:
#  ./get_dir_avail_space [dir]
#e.g:
#   ./get_dir_avail_space /root
#   ./get_dir_avail_space
 
本文永久更新地址:http://www.linuxdiyf.com/linux/32404.html