2

I have the below if statement. It gives me syntax error when I have both the csv file and the zip file in the folder. But it works when I have the csv file alone or the zip file alone or no files exist.

I'm not sure what causes the syntax error in the command below:

if [ -f ctf_error_report_??_????????????.csv -o -f ctf_error_report_??_????????????.???.zip ]; then echo "Successful" else echo "Problem" fi exit 0 

Any insight regarding this?

1
  • Use ksh -x your-script to see what gets executed. The chances are that the file name expansion expressions yield more than one file name, as the other people have diagnosed in their answers. Commented Oct 17, 2011 at 6:46

2 Answers 2

4

This is a dangerous way to check for files. If you happen to have more than one match in that directory then it won't work because each file will become a separate parameter, which won't match the syntax of the text. A better (although not foolproof) way to do it is like this:

set ctf_error_report_??_????????????.csv csv_file=$1 set ctf_error_report_??_????????????.???.zip zip_file=$1 if [ -f "$csv_file" -o -f "$zip_file" ] then echo "Successful" else echo "Problem" fi 
Sign up to request clarification or add additional context in comments.

2 Comments

could also say: set ...?.csv; n_csvfiles=$#; set ...?.???.zip; n_zipfiles=$#; if [ $n_csvfiles -gt 0 -0 $nzipfiles -gt 0 ]; ...
That won't work, because if the wildcard pattern doesn't match anything, it will just not be substituted, and $n_csvfiles will be 1.
1

I suspect you need this to test the success of some file transfer or report generation script (am I close?). The way I would do it (may not be the best, but it should work) is this:

#!/bin/bash FILE_FOUND=0 ls ./ctf_error_report_??_????????????.csv &>/dev/null if [ $? -eq 0 ]; then FILE_FOUND=1 fi ls ./ctf_error_report_??_????????????.???.zip &>/dev/null if [ $? -eq 0 ]; then FILE_FOUND=1 fi if [ $FILE_FOUND -eq 1 ]; then echo "Successful" else echo "Problem" fi 

This would return successful the moment the file pattern you're looking for is found in the directory of the script. You could change ./ for the full path of the files of course...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.