bash: error when counting number of files and comparing -


i new bash scripts. compare number of files have in directory using ls. , need compare number of files there variable have.

if [ (cd reports_dir/ && ls) | wc  -gt $maximum_reports ];     echo hello fi 

this code gives errors:

./monitor.sh: line 70: syntax error near unexpected token `cd' ./monitor.sh: line 70: `    if [(cd reports_dir/ && ls) | wc  -gt $maximum_reports]; then' 

i have idea why cd unexpected. command (cd reports_dir/ && ls) | wc works when run in terminal.

this command running in while loop called repeatedly. cannot cd directory attempts cd more once, resulting in error.

the command fails because need use command substitution syntax, otherwise expects value.

as noted, shouldn't changing directory cd - can use directory argument ls. wc command default returns count number of lines, words, , bytes , in expression need first one, should add argument wc -l.

other need decide if want include hidden files , use ls -a <dir> | wc -l. -a makes ls print files including hidden ones, excluding default . , ...

finally use double parentheses arithmetical comparison in condition clause:

if (( $(ls -a reports_dir | wc -l) > $maximum_reports ));     echo hello, read comment below fi 

having said that, above recipe work in majority of cases, mklement0's answer contains the correct solution.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -