0

I'm having issues with what I imagine should be a simple bash command

I'm basically just trying to loop through a bunch of files and get there names

`ls ./*.sql`               # list all files ending with .sql

if [ $? != 0 ]             # make sure such files exist
then
    echo "no such file"
else 
    echo "files exist"
fi

When I run

"ls ./*.sql"

I get what I expect

./file01.sql    ./file02.sql

However when I run the bash script I get

./file01.sql: line 1: some random error
./file01.sql: line 2: some random error
./file01.sql: line 3: some random error
./file02.sql: line 1: some random error
./file02.sql: line 2: some random error
./file02.sql: line 3: some random error

Anyone have any ideas why these would be different?

  • 1
    whats the use of putting ls command in between ` ? simply use ls ./*.sql – Edward Torvalds Apr 8 '15 at 9:40
  • 3
    You have unnecessarily tried a couple of uses of quotes of different kinds in contexts where they are typically not required. In case the answers below don't solve your problem or don't make clear how the typical constructs are written, please try to explain better what your problem is. – Janis Apr 8 '15 at 9:54
  • 1
    Always copy-paste error messages. Your question states that you're getting the error message “some random error”. Lying to us makes it hard to help you. Error messages are meaningful. – Gilles Apr 8 '15 at 21:12
3

It is the back tick quotes. They tell the shell to run the output of the command.

e.g.

`echo ls`

will run ls.

In your case you have asked bash to run the sql files. This is obviously not what you intended, as bash can not do this, the sql will not make sense to bash.

Also, even with this fix, the script will not do what you describe. Someone else (Janis) gave an answer to fix that as well, however they did not explain why your script did what it did.

  • the OP's script makes no sense with those various quotes, so it makes no sense to explain an unsensible use of them if they just don't belong there. – Janis Apr 8 '15 at 9:58
  • This is the answer I was looking for, I misunderstood the purpose of the back tick quotes, thanks a bunch – TheLovelySausage Apr 8 '15 at 10:10
2

To "loop through a bunch of [.sql] files and get their names" you'd just do:

for f in *.sql
do
    do_whatever_with_file "$f"
done

If you just want to list the files:

ls *.sql

If you want to test whether there are *.sql files existing, for example:

if  ls *.sql >/dev/null 2>&1
then echo sql files existing
else echo no sql files
fi

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.