Don't do that. Really, don't.
stat --format=%s testing.txt
...relies on having GNU stat, but is much more efficient and reliable (on any system where GNU stat is available).
filesize=$(stat --format=%s testing.txt)
...does the same thing, but saves the result into a variable named filesize
(just as you'd need to do with the ls
result to save its result for use anywhere else).
On a system without GNU stat, you might also consider:
filesize=$(wc -c <testing.txt)
...which will, if written by a sane person, seek to the end of the file and check its position, rather than reading all contents (a much more expensive test).
ls -l | grep testing.txt | cut -f6 -d' '
- lists all files (rather than looking only at the one file you care about), thus being much slower on large directories (with directories with tens of thousands of files or more, this could take minutes).
- filters only for names that contain
testing.txt
(where the .
can be any character -- it would find testingatxt
as well, or sometesting8txtbye.jpg
).
- dividing the results into columns by spaces, takes the 6th column from each line found.
Note that step 3
is particularly error-prone, because the specification for ls
doesn't make any promises about how many spaces will exist between each column in ls -l
, so there's no guarantee that this will work the way you expect.
See also Why You Shouldn't Parse the Output of ls(1).