2

Write command line that prints hello if number of files in current directory is bigger than the number specified in first line of file check.

This works fine but i want a one command line. Any ideas?

firstline=$(head -1 check)
allfiles=$(ls | wc -l)
echo $allfiles  $firstline

if (($allfiles > $firstline)); then
     echo "hello"
else 
     echo "oh no"
fi
4

You can use this one liner:

files=( * ); [[ ${#files[@]} -gt $(head -1 check) ]] && echo 'hello' || echo 'oh no'

files array will contain the files of the current directory, so ${#files[@]} shows the elements in the array i.e. number of files in the current directory.

The file check whose first line is a number is extracted by head -1 check.

Here is the expanded form :

Finally if number of files is greater than the number at the first line of check ([[ ${#files[@]} -gt $(head -1 check) ]]), hello is printed.

Here is the expanded form :

#!/bin/bash
files=( * )
if [[ ${#files[@]} -gt $(head -1 check) ]]; then
    echo 'hello'
else
    echo 'oh no'
fi
  • you are my Hero!!! – Martin Yeboah Jun 24 '15 at 17:37
  • @MartinYeboah Glad i could help :) – heemayl Jun 24 '15 at 17:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.