LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Simple bash problem - checking for files and displaying the first line (https://www.linuxquestions.org/questions/programming-9/simple-bash-problem-checking-for-files-and-displaying-the-first-line-298653/)

morrolan 03-07-2005 07:49 AM

Simple bash problem - checking for files and displaying the first line
 
Hi, I'm having a little problem with bash. I have gone through a couple of tutorials online for bash, but the only real language I've ever really used before is basic.

This looks nearly to right to me (famous last words!) but it isn't working.

This is a test of what I am trying to do - I am trying to list the contents of a directory of all text files with a certain extension (in this case *.txt). What I want to do is test if the files exist, and if they do, display the first line of each file.

in $HOME/lyrics are 2 files called 1.txt and 2.txt, and the first line of each contains a name of a song as a test.

Code:

#!/bin/bash


if [ ls $HOME/lyrics/*txt 1>/dev/null 2>&1 ]; then
        echo "Lyrics files found:"
        echo " "
        for i in $HOME/lyrics/*txt; do
                head -n 1 $i
        done
else
        echo "no text files found."
fi





All I ever get as a result is:

Code:

[me@mymachine me]$ /bin/bash lyrics.sh
No text files found.

Can anyone please tell me what I am doing wrong with the first part of the "if" for it not to give me any results?

keefaz 03-07-2005 10:07 AM

I would use find and a test variable like

Code:

#!/bin/bash

# test variable
found=
for file in $(find $HOME/lyrics -name "*.txt"); do
    [ -z $found ] && found=1
    head -n 1 $file
done

[ -z $found ] && echo "no text files found."

Also
Code:

if ls $HOME/lyrics/*txt 1>/dev/null 2>&1; then
will works too because the ls test is not supported with [], only the
files test or variables test work with [ ]

morrolan 03-07-2005 10:14 AM

Thanks for the tip, but like I said, i'm learning bash from scratch and this script is based on one I found on http://linuxcommand.org, but I just can't seem to get it to work.

It was taken from a larger script, but there were no variables set for it, the only difference is this IF was inside a function on it's own, but as I don't need anything else from the script, I don't need to define it as a function?


Thanks,
Morrolan

keefaz 03-07-2005 10:16 AM

The [ ] is a test for files, variables or result of test expression, ls is not a test expression
the [] is not testing the ls return value but instead if it is a positive test expression.

see man test ([] is an alias for test) and I edited my post, see how if ls can work

morrolan 03-07-2005 10:40 AM

Doh!

It was the [] test expression which was doing it - that's what I get for trying to be clever!

Thanks very much!!!


Morrolan


All times are GMT -5. The time now is 12:41 PM.