shell

文件

文件的操作主要是类型(目录,文件,块,套接字)判断,基本操作(创建,删除,遍历,属性修改),读写等;

类型判断

  • -a file exists.
  • -b file exists and is a block special file.
  • -c file exists and is a character special file.
  • -d file exists and is a directory.
  • -e file exists (just the same as -a).
  • -f file exists and is a regular file.
  • -g file exists and has its setgid(2) bit set.
  • -G file exists and has the same group ID as this process.
  • -k file exists and has its sticky bit set.
  • -L file exists and is a symbolic link.
  • -n string length is not zero.
  • -o Named option is set on.
  • -O file exists and is owned by the user ID of this process.
  • -p file exists and is a first in, first out (FIFO) special file or
    named pipe.
  • -r file exists and is readable by the current process.
  • -s file exists and has a size greater than zero.
  • -S file exists and is a socket.
  • -t file descriptor number fildes is open and associated with a
    terminal device.
  • -u file exists and has its setuid(2) bit set.
  • -w file exists and is writable by the current process.
  • -x file exists and is executable by the current process.
  • -z string length is zero.

例子

#!/bin/bash

if [ ! -f $1 ]; then
    echo "file=$1 not exist"
else
    echo "file=$1 exist"
fi

if [ ! -x $1 ]; then
    echo "file=$1 not exist or the file has not execution permission"
else
    echo "file=$1 and file has execution permission"
fi

创建文件

遍历文件夹

#!/bin/bash

if [ ! -d $1 ]; then
    echo "pleace input a directory"
    exit
fi

# the function can not deal with file with space
function list_files() {
    # param1: directory name to list, don`t state the variable for input parameter, it will work in iterator later,
    # you can use the keyword local to make the variable to work only in current function
    # clear the last /
    local directory=${1%*/}
    for file in `ls $directory`
    do
        path="$directory/$file"
        if [ -f $path ]; then
            echo "file=$path"
        elif [ -d $path ]; then
            echo "directory=$path"
            list_files "$path"
        else
            echo "unkown=$path"
        fi

    done
}

list_files $1

判断

循环

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容