cp:不能统计;使用dirname解析路径名并复制文件

时间:2016-01-10 00:45:24

标签: bash function grep ubuntu-14.04 cp

-

我需要通过读取/proc/[pid]/fd/目录中的文件描述符来复制进程已打开的每个文件。更具体地说,我需要找到每个pid的文件目录,然后egrep为正则表达式;以[0-9]$结尾的文件。 cp引发异常:

  

cp:无法统计'poop.log.2016-01-08T12-34-10':没有这样的文件或目录

function foo {
    local f
    logfile="$(logfile_for_pid)" # calls the function to get file descriptor
    for f in "$logfile"; do
            for i in "$(dirname "$f")"; do
                    echo "ls the dirname: "$i""
                    ls "$i" | egrep -e '[0-9]$' | xargs cp -t /tmp
            done
    done
}

我的问题是:如何将ls输出作为cp的参数传递?

也;直接从终端运行。同样的错误!注意;我是bash的新手!

$ cp `ls "$dir" | egrep -e '[0-9]$'` /tmp

1 个答案:

答案 0 :(得分:1)

很少有理由将ls实用程序的输出传递给任何东西。

我看着你的代码认为最外层的循环(f)很可能是不必要的,因为你在$logfile中存储的任何内容都将被视为任何一个文件名case(for f in "$logfile")。

这将其缩减为

function foo {
    logfile="$(logfile_for_pid)"

    for i in "$(dirname "$logfile")"; do
        echo "ls the dirname: "$i""
        ls "$i" | egrep -e '[0-9]$' | xargs cp -t /tmp
    done
}

可以消除内循环,因为我们知道只有一个$logfile

function foo {
    logfile="$(logfile_for_pid)"

    i="$(dirname "$logfile")"
    echo "ls the dirname: "$i""

    ls "$i" | egrep -e '[0-9]$' | xargs cp -t /tmp
}

现在,您要将该目录中文件名末尾带有数字的所有文件复制到/tmp

function foo {
    logfile="$(logfile_for_pid)"

    i="$(dirname "$logfile")"
    echo "ls the dirname: "$i""

    cp "$i"/*[0-9] /tmp
}

或者我误解了你?