linux - bash脚本在sftp下载完文件时就不再执行后面的命令?
伊谢尔伦
伊谢尔伦 2017-04-17 13:47:55
0
1
708

我有一段bash脚本如下,将远程机器上的数据库下载到本地进行使用:

#!/bin/bash  
sftp user@11x.1xx.1x.2xx<<EOF  
    get /var/www/app/db/app.db /home/user/db_bak/
    quit
EOF

mv /home/user/db_bak/app.db /var/www/app/db/
echo "done"

问题是文件下载完成,但是mv /home/user/db.bak/app.db /var/www/app/db/echo "done"并未执行,这是为什么呢?刚接触,goole了半天也没有结果,求大神指点。

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
Ty80

The path to save SFTP to local: /home/user/db_bak/
The local file path you gave the mv program: /home/user/db.bak/

Compare the differences between the two paths above. Give mv an incorrect local path and of course it won't move you.

I have never used sftp in a shell script. I don’t know if the execution of sftp will also give a signal to the shell to end, causing the following command to no longer be executed.

A personal suggestion: Why not use the relatively more secure and stable ssh (scp)? You don't have access to the server? If you have permission, it is recommended to use scp. This way you can save a few lines of commands

version 1:

#/usr/bin/env bash
scp user@ip:/file/path /home/user/local/path
mv /old/path/file /new/path/file
echo "Done!"

version 2: 加上判断,更准确一些
#/usr/bin/env bash
scp user@ip:/file/path /home/user/local/path
# 如果你从服务器复制到本地的是目录,就把下面中括号的 -f 改成 -d
if [ -f "/local/path/file" ]; then
    mv /local/path/file /new/path/file
else
    echo "文件不存在!"
fi

if [ -f "/new/path/file" ]; then
    echo "Done!"
else
    echo "目标目录文件不存在"
fi


version 3: 被你带跑偏了,为什么不能直接scp到最终的目录呢。唉...
#/usr/bin/env bash
echo "第一步:开始复制远程文件到本地"
scp user@ip:/var/www/app/db/app.db /home/user/db_bak/
if [ -f "/home/user/db_bak/app.db" ]; then
    echo "文件成功从服务器复制到本地!"
else
    echo "备份失败"
fi


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template