Score:0

Bash: improper function/usage of command basename

ca flag

What I want in the following command is to find particular files and move them to the other directories while appending ".log" to the destination filename.

find /src/dir/ -type f -mtime +3 -exec mv {} /dst/dir/`basename {}`.log \;

But it fails because the basename command enclosed in the backticks does not operate properly. $(basename {}) has similar result too.

mv: cannot move /src/dir/foo to /dst/dir//src/dir/foo.log: No such file or directory

Any idea would be appreciated.

Score:1
in flag

That's because the shell sees the `basename {}` or $(basename {}) before it handles the arguments to find and processes them. Write a script that does what you want and run it with -exec instead.

find ... -exec myscript {} \;

where myscript is something like

#! /bin/sh
mv "$1" /dst/dir/$(basename "$1").log

You can invoke the shell for each file found, so the following is also possible:

find ... -exec bash -c 'mv "$1" "$(basename "$1").log"' -- {} \;

But test such a solution properly to be sure quoting and escaping works correctly.

aschkant avatar
ca flag
Thanks @choroba for sharing. Since the line is a part of a script itself, I wonder if I could just simply add arguments to the -exec or totally in a single line to have the work done.
in flag
You can add arguments, but you can't use shell syntax on them - unless you try to write something like `-exec bash -c 'mv "$1" "$(basename "$1").log"' -- {} \;`
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.