How to verify that a file has more than 1 line in a BASH conditional expression?

I need to check if the file has more than 1 line. I tried this:

if [ `wc -l file.txt` -ge "2" ] then echo "This has more than 1 line." fi if [ `wc -l file.txt` >= 2 ] then echo "This has more than 1 line." fi 

They just report errors. How to check if a file has more than 1 line in a BASH conditional?

+8
bash conditional
source share
4 answers

Team:

 wc -l file.txt 

will generate output, for example:

 42 file.txt 

with wc , which also tells you the file name. It does this if you are viewing many files at the same time and want both individual and general statistics:

 pax> wc -l *.txt 973 list_of_people_i_must_kill_if_i_find_out_i_have_cancer.txt 2 major_acheivements_of_my_life.txt 975 total 

You can stop wc from doing this by submitting your data to standard input, so it does not know the file name:

 if [[ $(wc -l <file.txt) -ge 2 ]] 

The following decryption shows this in action:

 pax> wc -l qq.c 26 qq.c pax> wc -l <qq.c 26 

As an aside, you'll notice that I also switched to using [[ ]] and $() .

I prefer the former because it has fewer problems due to backward compatibility (mainly with line splitting), and the latter because it is much easier to embed executable files.

+19
source share

Pure bash (β‰₯4) capability using mapfile :

 #!/bin/bash mapfile -n 2 < file.txt if ((${#MAPFILE[@]}>1)); then echo "This file has more than 1 line." fi 

The built-in mapfile stores what it reads from stdin in an array (by default mapfile ), one row for each field. Using -n 2 allows you to read no more than two lines (for efficiency). After that, you only need to check if the mapfile array mapfile more than one field. This method is very effective.

As a by-product, the first line of the file is stored in ${MAPFILE[0]} if you need it. You will learn that the trailing newline character is not truncated. If you need to remove a newline, use the -t option:

 mapfile -t -n 2 < file.txt 
+5
source share

What about:

 if read -r && read -r then echo "This has more than 1 line." fi < file.txt 

The -r flag is necessary to ensure that line continuation characters do not stack two lines into one, which could lead to the following file reporting only one line:

 This is a file with _two_ lines, \ but will be seen as one. 
+4
source share
 if [ `wc -l file.txt | awk '{print $1}'` -ge "2" ] ... 

You should always check what each subcommand returns. The wc -l file.txt returns the result in the following format:

 12 file.txt 

You need the first column - you can extract it using awk or cut or any other utility of your choice.

+3
source share

All Articles