in reply to check for a remote file

Now imagine a GPRS link running at 9.600 bit/s and a 5 GByte file. The first line will run for days, fill your local memory and your swap, just to give you the information that the logfile existed when you started the cat command and had at least two lines.

To fix the two-lines problem, first compare with 0, not 1. This will give you a true value if the file exists and is not empty.

To really fix the problem, don't transfer the file at all. Use the remote shell:

my $flag=`ssh REMOTE_SERVER [ -f /tmp/somefile.log ] && echo 1`; chomp $flag; # not really needed

This will download at most two bytes, independant from the file size.

What happens here?

  1. ssh opens a shell to REMOTE_SERVER, then passes all remaining arguments to the shell.
  2. [ ] is a shortcut for the test command, the -f argument tells test to check if the next argument is the name of an existing file, and to return either success or failure. test is completely silent, it does not generate any output.
  3. && tells the shell to execute the right-hand-side command (echo) only if the left-hand-side command (test) returned success.
  4. echo 1 writes the digit 1 and a newline character to STDOUT.
  5. The backticks (``) collect what is written to STDOUT, dropping what is written to STDERR.
  6. Depending on the existence of a file named /tmp/somefile.log, $flag contains either "" (false) or "1\n" (true).
  7. chomp strips that final "\n".

Some notes:

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)