如何查找文件的大小并将其分配给UNIX中的变量 [英] How to find the size of a file and assign it to a variable in UNIX

查看:87
本文介绍了如何查找文件的大小并将其分配给UNIX中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个UNIX脚本,该脚本读取文本文件的大小,如果该文件具有某种大小,则应打印该文本文件.如果不是,则执行else循环,然后过程继续.

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 continues.

我正在使用以下命令来查找该文本文件的大小.

I am using the following command to find the size of that text file.

ls -l ${filepath}/{filename}.lst | awk '{print $5}'

如何将其分配给脚本中的变量并将其置于if条件中?
还是例如if条件应该像if[$var==461]这样可以工作吗?

How do I assign it to a variable inside the script and put it in an if condition?
or example the if condition should be like if[$var==461] does this work?

或者我可以使用其他命令来查找文件的大小吗?

or is there any other command i can use to find the size of the file?

推荐答案

您可以使用stat命令,从而无需使用awk.

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

例如在具有bash的linux中,其中 myfile 是您的文件路径:

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

记下等号命令-eq注释,该命令是bash中的算术二进制运算符.

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

这篇关于如何查找文件的大小并将其分配给UNIX中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆