Unable to use wildcard for SSH command

2020-03-26 07:31发布

问题:

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?

回答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.



回答2:

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