简体   繁体   中英

Shell script with ssh command with an if statement

I want to write a shell script to do the following:

  1. login some remote machines, say host1 and host2, each at a time
  2. go to the /tmp directory and check whether a particular directory named 'dirname' exists or not. If it doesn't exist, make a directory 'dirname'
  3. go to the directory /tmp/dirname
  4. copy a file with a variable runNo from the local machine to this directory

I tried something like this, but it doesn't work.. any help would be much appreciated. Thanks!

#! /bin/bash
dir1=dirname
runNo=0

for i in 1 2
do
  runNo=$(($runNo+1))
  echo "host$i runNo$runNo"

  ssh host$i "cd /tmp;
    if [ -d $dir1 ]; then
      cd $dir1;
    else
      mkdir $dir1;
      cd $dir1;
    fi;
    cp ~/local/file$runNo file"

  echo "done"
done

How about

ssh host$i "mkdir -p /tmp/$dir1"
scp ~/local/file$runNo host$i:/tmp/$dir1/file

mkdir -p suppresses errors if the directory already exists.

Like this perhaps?

runNo=1
for h in host1 host2; do
    cat ~/local/file$runNo |
    ssh "$h" 'mkdir -p /tmp/dirname; cat >/tmp/dirname/file'
    runNo=$(($runNo+1))
done

If I interpret your description correctly, the cd is superfluous.

If Bourne shell compatibility is necessary, you can replace the increment with

    runNo=$(expr $runNo + 1)

Try this:

ssh -t -t host$i <<eod1
echo "your command goes here"
add eod1 to terminate your ssh
eod1

Note two -t -t is required to overwrite the sudo terminal error

this editing rules is driving me crazy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM