linux - OS X/Linux 上的 bash 脚本练习

标签 linux macos bash

我必须做一个练习:有一个包含此文本的文件

目录A 目录B

dirX dirY

dirA dirD

每一行有两个目录,脚本必须检查每一行第二个目录中是否包含第一个目录的任何文件。这是脚本:

if [ $# -ne 2 ];then
echo "Error! Insufficient parameters"
exit 1
fi
if [ ! -f $1 ];then
echo "$1 is not a file"
exit 2
fi
if [ -f $2 ];then
echo "$2 already exists"
exit 3
fi

file=$(cat $1)
file_output=$(touch $2)
count=0
dir_a=''
dir_b=''

for i in $file ; do
    if [ $count -eq 0 ];then
        dir_a=$i
        let count=$count+1
        continue
    fi
    if [ $count -eq 1 ];then
        dir_b=$i
        let count=0
        for f in $(ls $dir_a) ; do
            if [ -f $dir_b/$f ];then
                echo "found"
            fi
        done
    fi
done

问题是它不检查最后一对,在上面的示例中,它不会检查“dirA dirD”这对。 对于这种奇怪的行为有什么想法吗?

最佳答案

...什么?

while read src dest
do
  for file in "$src"/*
  do
    if [ -e "$dest"/"${file##*/}" ]
    then
      echo "Found: $src $dest"
      break
    fi
  done
done

关于linux - OS X/Linux 上的 bash 脚本练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14377097/

相关文章:

linux - 定位命令未检测到 32 位库

linux - 防止用户从 unix 中的某个目录中执行某个命令

python - os.system(cmd) 与终端中的 cmd 不同

linux - 使用 "read"设置变量

php - 在 Imagemagick for linux 中,如何对目录进行批量转换

mysql - 每 5 秒获取 MySQL 进程列表日志

macos - OS X cocoa : NSDocument-Based Application not saving

xcode - 如何检索当前接收按键事件的 OSX 应用程序

java - jvisualvm 去哪儿了?

Bash:在 if 语句中使用 diff 的结果