3

There are a number of files that I have to check if they exist in a directory. They follow a standard naming convention aside from the file extension so I want to use a wild card e.g:

YYYYMM=201403
FILE_LIST=`cat config.txt`
for file in $FILE_LIST
do
    FILE=`echo $file | cut -f1 -d"~"`
    SEARCH_NAME=$FILE$YYYYMM
    ANSWER=`ssh -q userID@servername 'ls /home/to/some/directory/$SEARCH_NAME* | wc -l'`
    returnStatus=$?
    if [ $ANSWER=1 ]; then
        echo "FILE FOUND"
    else
        echo "FILE NOT FOUND"
    fi
done

The wildcard is not working, any ideas for how to make it visible to the shell?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175
Blue42
  • 139
  • 4
  • 13
  • 3
    Use double quotes in your `ssh` command, so that the variable will get expanded. – fedorqui Mar 24 '14 at 14:24
  • 1
    style: get out of the habit of using ALL_CAPS_VARNAMES -- you'll use PATH one day and break your script. – glenn jackman Mar 24 '14 at 15:16
  • Note: this will always be true, no matter what $ANSWER holds: `[ $ANSWER=1 ]` -- when given a single argument `test` returns "true" if the argument in not empty. You meant `[ $ANSWER -ne 0 ]` with spaces around the operator – glenn jackman Mar 24 '14 at 15:17
  • possible duplicate of [Bash variable expansion in command](http://stackoverflow.com/questions/18974952/bash-variable-expansion-in-command) – tripleee Mar 25 '14 at 11:54

2 Answers2

1

I had much the same question just now. In despair, I just gave up and used pipes with grep and xargs to get wildcard-like functionality.

Was (none of these worked - and tried others):

ssh -t r@host "rm /path/to/folder/alpha*"    
ssh -t r@host "rm \"/path/to/folder/alpha*\" "
ssh -t r@host "rm \"/path/to/folder/alpha\*\" "

Is:

ssh -t r@host "cd /path/to/folder/ && ls | grep alpha | xargs rm"

Note: I did much of my troubleshooting with ls instead of rm, just in case I surprised myself.

sage
  • 4,863
  • 2
  • 44
  • 47
-1

It's way better to use STDIN:

echo "rm /path/to/foldef/alpha*" | ssh r@host sh

With this way you can still use shell variables to construct the command. e.g.:

echo "rm -r $oldbackup/*" | ssh r@host sh
  • You can still use shell variables; just make sure you're using double quotes not single quotes: `ssh r@host "rm -r $oldbackup/*"` – roaima May 01 '21 at 06:36