如何遍历子目录中的一组文件并对其进行操作

时间:2013-10-24 20:01:54

标签: bash shell unix dotfiles

我正在尝试将thoughtbot's bash script修改为符号链接dotfiles到主目录中,但我想将我的文件存储在子目录中。

思想机器人脚本中的原文是:

#!/bin/sh

for name in *; do
  target="$HOME/.$name"
  if [ -e "$target" ]; then
    if [ ! -L "$target" ]; then
      echo "WARNING: $target exists but is not a symlink."
    fi
  else
    echo "Creating $target"
    ln -s "$PWD/$name" "$target"
  fi
done

我的dotfiles位于名为files的子目录中。我尝试将for循环更改为:

for name in files/*for name in ./files/*for name in 'files/*'等,但这些都不起作用。

经过一番研究后,我发现您可以使用find循环遍历子目录中的文件,如下所示:

find ./files -type f -exec "do stuff here"  \;

我看到我可以使用'{}'来引用每个文件,但我不明白我如何操作该文件并制作符号链接。

我试过了:

find ./files -type f -exec "ln -s '{}' $HOME/'{}'"  \;

但这不起作用,因为'{}'是来自父目录的文件的相对路径,而不仅仅是文件的名称。

这样做的正确方法是什么?

作为参考,这就是我的目录结构:

https://github.com/mehulkar/dotfiles

2 个答案:

答案 0 :(得分:1)

您的原始脚本不适用于dotfiles,因为您需要说:

shopt -s dotglob

for file in *

默认情况下不会匹配以dot开头的文件名。

答案 1 :(得分:0)

  

...   但这不起作用,因为'{}'是文件的相对路径   来自父目录,而不仅仅是文件的名称。

尝试

find `pwd`/files -type f -exec "ln -s '{}' $HOME/'{}'"  \;

find $(pwd)/files -type f -exec "ln -s '{}' $HOME/'{}'"  \;