-1

I'm trying to figure out a way to perform the following loop on a remote host via ssh.

Basically it renames a series of directories to create a rotating backup. But it's local. I want it to work against directories on a remote host.

while [ $n -gt 0 ];
    do {
    src=$(($n-1))
    dst=$n
    if [ -d /backup/$src ];
    then {
    mv /backup/$src /backup/$dst;
    }
    fi;
    }
    ((n--))
done;
I Forgot
  • 1
  • 2

2 Answers2

3

If you're using bash, you'll want to use [[ and ]] instead of [ and ]. It makes it much easier to do comparisons like you're doing here.

First, what is $n's starting value?

Try this:

ssh usr@host 'for n in {10..1}; do [[ -d /backup/$(($n-1)) ]] && /bin/mv /backup/$(($n-1)) /backup/${n}; done'

That right there should do it. That's assuming your starting number is 10. Depending on where $n is coming from, that can be modified. Notice that mv has the full path specified... this is because when you execute a remote session in ssh, it tends not to execute your .bashrc and .bash_profile meaning you don't have a ${PATH} yet set. There might be a way around it, but I don't know what it is.

Written out more human-readably:

for n in {10..1}
do
  if [[ -d /backup/$src ]]
  then
    /bin/mv /backup/$src /backup/$dst
  fi
fi

Since you're executing it remotely, I figured it would be easier in a single line.

UtahJarhead
  • 908
  • 7
  • 14
2

Place the script in a file on your local machine, e.g. backup.sh and run the remote execution like this:

ssh user@remotehost < backup.sh

This allows you to run the script on the remote host without actually copying it to the remote host.

I use this method for gathering hardware specifications from remote systems.

ewwhite
  • 194,921
  • 91
  • 434
  • 799