【问题标题】:Bash script to loop through remote directory and pipe files 1 at a time to CURLBash脚本循环遍历远程目录和管道文件一次1个到CURL
【发布时间】:2020-08-23 01:38:02
【问题描述】:

我正在尝试通过在 Server2 上运行的脚本将 Server1 上指定目录中的所有文件传输到 Server3。

到 Server3 的传输必须通过 API 进行,因此必须使用以下 CURL 调用:

curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header "Authorization: Bearer $token" \
    --header "Dropbox-API-Arg: {\"path\": \"/xfer/$name\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}" \
    --header "Content-Type: application/octet-stream" \
    --data-binary @$f

如果它只是 1 个文件,我可以成功,但我试图遍历 Server1 上的目录并将文件直接发送到 CURL 调用。到目前为止,我得到了:

files="( $(ssh me@server1 ls dir/*) )"
while read f 
do
  name=$(basename ${f})
  curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header "Authorization: Bearer $token" \
    --header "Dropbox-API-Arg: {\"path\": \"/xfer/$name\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}" \
    --header "Content-Type: application/octet-stream" \
    --data-binary @$f
done <<< "$files"

循环似乎正在将文件数组中的“(”读取到第一个文件名中,这显然会导致问题。我无法超越这一点来判断是否在循环中发布当前文件via --data-binary 实际上会按照我的想法(或希望)做。

有什么办法吗?

【问题讨论】:

  • 你为什么有那些额外的外括号?
  • 创建一个数组,这样带有空格的文件名就不会被分成多个字符串,但这似乎不起作用,因为echo ${#files[@]} 返回1,即使有多个文件。我做错了什么?

标签: bash loops curl pipe remote-server


【解决方案1】:

原始消息中的错误是将 ssh 命令包含在 "()" 中。我正在研究类似的问题。过去我使用过 Rsync,但我想要一个不需要安装额外软件的解决方案。这是我正在使用的一个示例,用于将文件从 Nodejs 开发服务器上移出以进行备份,在 Debian 上的 Bash 中运行:

files=$(ssh chris@estack ls ~/tmp/gateway)
#echo $files
for FILE in $files
do

  if [[ "$FILE" = "node_modules" || "$FILE" = ".git" ]]
  then
    echo "skip $FILE";
    continue
  fi

  echo Copy ~/tmp/gateway/$FILE
  #scp -Cpr chris@estack:~/tmp/gateway/$FILE ~/tmp/tmp
done

【讨论】:

  • 如果您的文件名包含空格,这是否有效?我的猜测是像my data.csv 这样的文件名将被视为2 个文件,mydata.csv,你会得到no such file 错误,但更重要的是,my data.csv 不会被复制。无论如何,这就是我所遇到的。
  • 你是对的。我的最终代码使用这种模式:scp -Cpr chris@estack:~/tmp/gateway/"$FILE" ~/tmp/tmp。另外,请注意,许多人推荐这种模式:scp -Cpr chris@estack:~/tmp/gateway/"${FILE}" ~/tmp/tmp。有关详细信息,请参见以下内容:Google's Shell Style Guide
猜你喜欢
  • 2013-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-11
  • 1970-01-01
相关资源
最近更新 更多