为什么运行此命令会给我错误消息:没有这样的文件或目录?
for i in `find ~/desktop -name '*.py'` ; do ./$i ; done
答案 0 :(得分:1)
完整的错误消息使您更清楚地了解问题所在:
bash: .//home/youruser/desktop/foo.py: No such file or directory
您可以看到确实没有这样的文件:
$ .//home/youruser/desktop/foo.py
bash: .//home/youruser/desktop/foo.py: No such file or directory
$ ls -l .//home/youruser/desktop/foo.py
ls: cannot access './/home/youruser/desktop/foo.py': No such file or directory
以下是如何运行文件/home/youruser/desktop/foo.py
:
$ /home/youruser/desktop/foo.py
Hello World
因此要在循环中运行它,您可以执行以下操作:
for i in `find ~/desktop -name '*.py'` ; do $i ; done
这是做同一件事的更好方法:
find ~/desktop -name '*.py' -exec {} \;
或带有shell循环:
find ~/desktop -name '*.py' -print0 | while IFS= read -d '' -r file; do "$file"; done
有关./
是什么和做什么以及为什么在这里没有意义的解释,请参见this question
答案 1 :(得分:0)
尝试查找和 exec 选项。 http://man7.org/linux/man-pages/man1/find.1.html
-exec command ;
Execute command; true if 0 status is returned. All following
arguments to find are taken to be arguments to the command
until an argument consisting of `;' is encountered. The
string `{}' is replaced by the current file name being
processed everywhere it occurs in the arguments to the
command, not just in arguments where it is alone, as in some
versions of find. Both of these constructions might need to
be escaped (with a `\') or quoted to protect them from
expansion by the shell. See the EXAMPLES section for examples
of the use of the -exec option. The specified command is run
once for each matched file. The command is executed in the
starting directory. There are unavoidable security problems
surrounding use of the -exec action; you should use the
-execdir option instead.
-exec command {} +
This variant of the -exec action runs the specified command on
the selected files, but the command line is built by appending
each selected file name at the end; the total number of
invocations of the command will be much less than the number
of matched files. The command line is built in much the same
way that xargs builds its command lines. Only one instance of
`{}' is allowed within the command, and (when find is being
invoked from a shell) it should be quoted (for example, '{}')
to protect it from interpretation by shells. The command is
executed in the starting directory. If any invocation with
the `+' form returns a non-zero value as exit status, then
find returns a non-zero exit status. If find encounters an
error, this can sometimes cause an immediate exit, so some
pending commands may not be run at all. This variant of -exec
always returns true.
答案 2 :(得分:0)
find
语句返回的路径将是绝对路径,例如〜/ desktop / program.py。如果将./
放在它们前面,则会得到./~/desktop/
之类的不存在的路径。
用./$i
替换"$i"
(用引号引起来的文件名带有空格等)。
答案 3 :(得分:0)
您应该使用$ i而不是./$ i
我在这一刻正做着同样的事情。我想要一个脚本来查找目录中是否有任何flac文件并将其转换为opus。
这是我的解决方法:
if test -n "$(find ./ -maxdepth 1 -name '*.flac' -print -quit)"
then
do this
else
do nothing
fi