How to find the size of a file and assign it to a

2019-02-28 09:44发布

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}'

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?

4条回答
冷血范
2楼-- · 2019-02-28 10:18

Simply put it as-

var=$(ls -l ${filepath}/{filename}.lst | awk '{print $5}')
查看更多
老娘就宠你
3楼-- · 2019-02-28 10:19

I wouldn't recomment stat which is not portable not being specified by POSIX.

Here is a safer way to get the file size in a variable.

size=$(ls -dnL -- "${filepath}/{filename}.lst" | awk '{print $5;exit}')
查看更多
你好瞎i
4楼-- · 2019-02-28 10:33

Assign your file size in a variable and then check equality with -eq

size=`ls -l ${filepath}/{filename}.lst| awk '{print $5}'`
if [ $size  -eq 461 ]
then
   echo "MATCHED"
else
  echo "NOT MATCHED"
fi
查看更多
Fickle 薄情
5楼-- · 2019-02-28 10:37

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
查看更多
登录 后发表回答