命令在终端中运行,但不是通过/ bin / sh

时间:2013-02-01 00:18:01

标签: linux bash shell

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

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"

ERROR:

/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附加到它们。这是我第一次看到这个问题。有什么建议吗?

1 个答案:

答案 0 :(得分: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 {} \;"
相关问题