How to find the size of a file and assign it to a variable in UNIX

前端 未结 4 625
借酒劲吻你
借酒劲吻你 2021-01-23 09:36

I am writing a UNIX script that reads the size of a text file and if the file is of some size it should print the text file. If it is not an else loop executes and the process c

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-23 10:15

    You can use the stat command which eliminates the need to use awk.

    For example in in linux with bash where myfile is your file path:

    sz=$(stat -c '%s' myfile)
    if [ $sz -eq 100 ]; then
        echo "myfile is 100 bytes"
    fi
    

    Take note of the equality command -eq that's the arithmetic binary operator in bash.

    Alternatively you can use a variable for the file path:

    f=my/file/path
    sz=$(stat -c '%s' $f)
    if [ $sz -eq 100 ]; then
        echo "$f is 100 bytes"
    fi
    

提交回复
热议问题