How can I use ls *.txt | wc
as a separate variable so I can use it in a loop afterwards? That is
count.files=$(ls *.txt | wc)
...
if count.files -ne 2000; then
echo "message"
fi
I have tried it but it seems it doesn't work.
There are several mistakes in you code:
wc
with the -l
flagls
with the -d
flag--
or use a ./
prefix for ls
if
test misses brackets (but maybe that's just stackexchange formatting)Here is a better working example:
file_count=$(ls -d ./*.txt | wc -l)
if [ $file_count -ne 2000 ]; then echo "message"; fi
I think the feature you're thinking of is disciplines. That's a ksh93
-only feature:
function count.get {
.sh.value=$(set -- ~(N)*.txt; echo "$#")
}
Then, whenever $count
is expanded, that discipline function is invoked that assigns a value to it.
In zsh
, you can also define the content of a variable as code:
count='$(set -- *.txt(N); echo "$#")'
and use it as ${(e)count}
for that code to be evaluated upon expansion.
However those give little benefit over the standard way of using a function:
count() (
set -- [*].txt *.txt
case $1$2 in
'[*].txt*.txt') echo 0;;
*) echo "$#"
esac
)
(the [*]
trick can be avoided with shells that support nullglob options (like ksh93
's ~(N)
or zsh
's (N)
above)).
And use it as $(count)
(command substitution).
(see the other answers for all the issues with your code).
First of all you need to use wc -l
to count only newlines. This should work:
#!
filecounter=$(ls *.txt | wc -l)
if [ $filecounter -ne 2000 ]; then echo "message"
fi
count_files=$(ls *.txt | wc -l);if [ ${count_files} -ne 2000 ]; then echo "message";fi
$
in variable substitution and missing[]
brackets for-ne
to make sense.if
is only a member of a loop that does include some mechanism to decrease the number of files being counted, this will result in an infinite loop.for file in *.txt; do ...; done
?