Search code examples
bashshellcommand-substitution

File count in a folder not showing accurate


I am writing a shell script to check two things at one time. The first condition is to check for the existence of a specific file and the second condition is to confirm that there is only one file in that directory.

I am using the following code:

conf_file=ls -1 /opt/files/conf.json 2>/dev/null | wc -l 
total_file=ls -1 /opt/files/* 2>/dev/null| wc -l

if [ $conf_file -eq 1 ] && [ $total_file -eq 1 ]
then
    echo "done"
else
    echo "Not Done"
fi

It is returning the following error

0
0
./ifexist.sh: 4: [: -eq: unexpected operator
Not Done

I am probably doing a very silly mistake. Can anyone help me a little bit?


Solution

  • One of the reasons you should normally not parse ls is that you can get strange results when you have files with newlines. In your case that won't be an issue, because any file different from json.conf should make the test fail. However you should make the code counting the files be future-proof. You can use find for this.

    Your code can be changed into

    jsonfile="/opt/files/conf.json"
    countfiles=$(find /opt/files -maxdepth 1 -type f -exec printf '.\n' \; | wc -l)
    
    if [[ -f "${jsonfile}" ]] && (( "${countfiles}" == 1)); then
      echo "Done"
    else
      echo "Not Done"
    fi