As others have pointed out, this is not an accurate way to count the number of files you have. It will miscount files that contain newlines for example and can have other issues.
It is, however, a perfectly good way to count the number of lines that ls
will print and not show them if they're too many which is what you're presumably trying to do.
So, to answer your general question, to make one command depend on the result of another, you can use one of
command1 && command2
That will run command2
only if command1
was successful. If you want the second to be executed only if the first's results pass some test you can use:
[ command1 ] && command2
For your example, that would be:
[ $(ls | wc -l) -gt 100 ] && echo too many
To also execute ls
again if the test is passed, use either
[ $(ls | wc -l) -gt 100 ] && echo too || ls
or
if [ $(ls | wc -l) -gt 200 ]; then echo 'too many files!'; else ls; fi
However, all of these are inelegant since they need to run the command twice. A better way might be to run the command once, save its output to a variable and then test the variable:
x=$(ls); [ $(wc -l <<<"$x") -gt 100 ] && echo 'too many!' || printf "%s\n" "$x"
Here, the output of ls
is saved in the variable $x
, then that variable is given as input to wc
and if it has more than 100 lines, a message is printed. Else, the variable is.
For the sake of completeness, here's another safe approach that will count files correctly:
[ $(find -maxdepth 1 | grep -cF './') -gt 100 ] && echo 'too many!' || ls