1

如果我运行此命令,它在终端中可以正常工作:

for dirname in $(ls -d dir/checkpoint/features.txt/20*);do;echo "hello";done

但是当通过 /bin/sh -c 运行时,它会给出一个错误

/bin/sh -c "for dirname in $(ls -d dir/checkpoint/features.txt/20*);do;echo "hello";done"

错误:

/bin/sh: -c: line 1: syntax error near unexpected token `dir/checkpoint/features.txt/201108000'
/bin/sh: -c: line 1: `dir/checkpoint/features.txt/201108000'

我的默认 shell 是 /bin/bash。我似乎无法理解是什么原因造成的。我在程序中运行所有 shell 命令的默认实现是将 /bin/sh -c 附加到它们。这是我第一次看到这个问题。有什么建议么?

4

1 回答 1

2

不要尝试解析 的输出ls,尤其是使用for构造时。有很多很多方法会出错。

这是一个使用的好地方find。试试这个:

/bin/sh -c "find dir/checkpoint/features.txt -mindepth 1 -maxdepth 1 -type d -iname '20*' -exec echo \"hello\" \;"

除了消除容易出错的使用之外ls,您还避免了子 shell 及其带来的所有问题。

跟进您的评论:

我假设您正在使用awk -F/ '{print $NF}'获取文件所在文件夹的名称(即文件名之前的最后一个目录名称)。这些命令basenamedirname用于为您执行此操作。这应该使您的脚本更容易一些。将以下内容放入脚本文件中:

#!/bin/sh
folder=$(basename $(dirname $1))
mkdir -p #{nfs_checkpoint}/${folder}
cat #{result_location}/${folder}/20* > #{nfs_checkpoint}/${folder}/features.txt

并像这样执行它:

/bin/sh -c "find dir/checkpoint/features.txt -mindepth 1 -maxdepth 1 -type d -iname '20*' -exec yourscript.sh {} \;"
于 2013-02-01T00:35:55.383 回答