如何检查文件的大小是否大于 Bash 中的某个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46824020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a file's size is greater than a certain value in Bash
提问by bipster
Okay, beginner here:
How do I achieve the following goal:
好的,这里是初学者:
我如何实现以下目标:
- I need to check the size of a file
- Then compare this file size to a fixed number using an if condition and corresponding conditional statement
- 我需要检查文件的大小
- 然后使用 if 条件和相应的条件语句将此文件大小与固定数字进行比较
So far, I have the following:
到目前为止,我有以下几点:
#!/bin/bash
# File to consider
FILENAME=./testfile.txt
# MAXSIZE is 5 MB
MAXSIZE = 500000
# Get file size
FILESIZE=$(stat -c%s "$FILENAME")
# Checkpoint
echo "Size of $FILENAME = $FILESIZE bytes."
# The following doesn't work
if [ (( $FILESIZE > MAXSIZE)) ]; then
echo "nope"
else
echo "fine"
fi
With this code, I can get the file name in the variable $FILESIZE, but I am unable to compare it with a fixed integer value.
使用此代码,我可以在变量 $FILESIZE 中获取文件名,但无法将其与固定整数值进行比较。
EDIT
编辑
#!/bin/bash
filename=./testfile.txt
maxsize=5
filesize=$(stat -c%s "$filename")
echo "Size of $filename = $filesize bytes."
if (( filesize > maxsize )); then
echo "nope"
else
echo "fine"
fi
回答by Inian
Couple of syntactic issues.
几个语法问题。
- The variable definitions in
bash
do not take spaces it should have beenMAXSIZE=500000
, without spaces - The way comparison operation is done is incorrect. Instead of
if [ (( $FILESIZE > MAXSIZE)) ];
. You could very well usebash
's own arithmetic operator alone and skip the[
operator to justif (( FILESIZE > MAXSIZE)); then
- 中的变量定义
bash
不使用它应该使用的空格MAXSIZE=500000
,没有空格 - 比较操作的方式不正确。而不是
if [ (( $FILESIZE > MAXSIZE)) ];
. 您可以很好地bash
单独使用自己的算术运算符并跳过[
运算符仅if (( FILESIZE > MAXSIZE)); then
If you are worried about syntax issues in your script, use shellcheckto syntax check your scripts and fix the errors as seen from it.
如果您担心脚本中的语法问题,请使用shellcheck对脚本进行语法检查并修复从中看到的错误。
As a general coding practice lowercaseuser-defined variables in bash
to avoid confusing them with the special Environment variables which are interpreted for different purposes by the shell (e.g. $HOME
, $SHELL
)
作为一般的编码实践,小写用户定义的变量是bash
为了避免将它们与由 shell 解释为不同目的的特殊环境变量混淆(例如$HOME
,$SHELL
)