Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to do a script to look in some folders and send an email if there are files in these folders.
I've tried to do something like this but I get errors with the command variable and print of the folder.

for folder in "FOLDER1" "FOLDER2";  do
  command=`ssh -q user@host "ls /usr/local/username/`{print $folder}` | wc -l"`
  #echo $command

  if [ $command -ne '0' ]
  then
    #send error email 
  fi
done
share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

You should try with:

command=$(ssh -q user@host 'ls "/usr/local/username/'$folder'" | wc -l')

You can't really nest backticks (and I'm not sure why you wanted to to that anyway).

share|improve this answer
    
it works! thanks a lot –  simone May 17 '12 at 10:21
add comment

This can be a lot simpler. I have no idea what you're tring to do with {print $folder}: the braces don't make any sense here, and if you're trying to include $folder in the string, you would just write $folder. You should not parse the output of ls, it's very rarely useful and often fails.

if ! ssh user@host "test -e '/usr/local/username/$folder'"; then
  # the file doesn't exist

Note that the file name must be quoted for the remote shell. I mostly took care of this in my command above, by surrounding the file name in the remote command with single quotes, but that only works if $folder itself does not contain any single quotes. If your local shell is bash, ksh93 or zsh, use this instead, to quote any single quote:

q=\'\\\'\'
if ! ssh user@host "[ -d '/usr/local/username/${folder//\'/$q}' ]"; then

Another approach which is usually more convenient is to mount the remote filesystem with sshfs and work on it through the normal filesystem interface. I recommend this unless you're working with a lot of remote servers at the same time.

mkdir /path/to/mount/point
sshfs user@host /path/to/mount/point
if ! [ -d "/usr/local/username/$folder" ]; then
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.