linux - for 循环中 if 语句中的 if 语句

标签 linux bash

似乎当您在循环内的 if 语句中使用 if 语句时,if 语句不会遍历每个元素。

我应该如何解决这个问题?

使用以下代码,我试图将所有无法执行的 .py 文件放入 1.log 中。但它只将在 1.log 中找到的第一个 python 文件放入。

for i in `find ~/desktop -name '*.py'` ; do 
  if $i ; then 
    true
  else 
    if [[ -e "1.log" ]];then
      echo "$i" > 1.log
    fi
  fi   
done

最佳答案

您正在使用 > 重定向,它将替换所有文件内容。使用 >>> 来连接。

此外,在开始循环之前确保文件存在(我为此添加了一个touch命令)

touch 1.log
for i in `find ~/desktop -name '*.py'` ; do 
  if $i ; then 
    true
  else 
    if [[ -e "1.log" ]] ; then
      echo "$i" >> 1.log
    fi
  fi   
done

关于linux - for 循环中 if 语句中的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54890279/

相关文章:

linux - 一个目录中的所有文件,linux

bash - 如何在 for 循环中循环选择一小组选项?

linux - bash 管道处理

Bash:捕获在后台运行的命令的输出

linux - 在 winSCP 中切换用户

linux - 如何使用来自外部服务器 linux 的数据启动本地程序

bash - 如何 sudo su;然后运行命令

linux - 在所有子目录上使用 wc 来计算行数

c - 程序在 Linux 和 Windows 上挂起,似乎在 Mac 上运行

c - 在不更改代码的情况下使用 gcc 的功能多版本控制是否可行?