【问题标题】:Get output of FOR with EOF in bash在 bash 中使用 EOF 获取 FOR 的输出
【发布时间】:2017-02-03 23:20:18
【问题描述】:

我创建了一个 bash 脚本来临时帮助我根据提交的 id 将一些文件发送到 FTP 服务器,我得到最后一次提交,跟踪文件并按照下面列出的方式发送。

#!/bin/bash

commit_hash=$(git log --format="%H" -n 1)

[[ -z "$1" ]] || commit_hash=$1

files=$(git diff-tree --no-commit-id --name-only -r $commit_hash)

echo -e $(git log -1 $commit_hash --pretty=format:"%h - %an, %ar : %s");
printf "\n"

HOST=
USER=
PASS=

for file in $files; do
ftp -nv $HOST << EOF
user $USER $PASS
cd /www/example
passive
put $file
bye
EOF

done;

当然这不是最好的方法,但我自动化了一些我目前正在做的事情。

是否可以捕获 heredoc 的 ftp 输出并应用一些过滤器?以管道为例,我只想知道传输是否成功完成。

【问题讨论】:

  • 用$? bash 变量检查ftp 的退出状态码怎么样?它可能包含足够的信息来确定请求是否成功。

标签: linux git bash shell scripting


【解决方案1】:

是否可以捕获 heredoc 的 ftp 输出并应用一些过滤器?以管道为例,我只想知道传输是否成功完成。

我猜你的意思是你想捕捉ftp 命令的输出,它的输入是从heredoc 重定向的;从某种意义上说,heredoc 本身没有任何输出,除了相关命令之外的任何东西都可以看到。

但是你可以重定向命令的输出。要记住的是,heredoc 从下一行开始,而不是紧跟在关联的重定向运算符之后。因此,您可以在 heredoc 运算符之后将管道添加到另一个命令。例如:

$ cat << EOF | grep flag
flag this line
not this line
or this line
flag this
last flag
EOF

输出:

flag this line
flag this
last flag

【讨论】:

    【解决方案2】:

    不要为此使用for 循环。见Bash FAQ 001。

    commit_hash=${1:-$(git log --format="%H" -n 1)}
    
    while IFS= read -r file; do
      ftp -nv "$HOST" << EOF
    user $USER $PASS
    cd /www/example
    passive
    put $file
    bye
    EOF
    done < <(git diff-tree --no-commit-id --name-only -r "$commit_hash")
    

    【讨论】:

      猜你喜欢
      • 2014-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2018-05-21
      • 2017-12-19
      • 2019-03-19
      • 2021-12-29
      相关资源
      最近更新 更多