我试图在bash中完成一些简单的操作:查找文件夹中的文件,并在存在的情况下获取它们(如果没有文件,则不输出)。
在Bourne炮弹这是如何做到这一点:
如果[-d /etc/profile.d]; 然后
对于`ls -1 /etc/profile.d/*.sh 2> / dev / null`中的f; 做
。 $ F
DONE
科幻
我是zsh的新手,无法获得相应的工作。 我究竟做错了什么?
如果[[-d“/etc/zsh.d”]]; 然后
(ls -1 /etc/zsh.d/*.zsh 2> / dev / null)中的文件。 做
源$文件
DONE
科幻
失败: parse error near '>' 。
我已经尝试了很多变化,不能像sh / bash那样平滑。 就好像redirect不总是在子壳内工作。
之后通过电子邮件发送给zsh用户邮件列表,我得到了近乎理想的解决scheme:
如果[[-d“/etc/zsh.d”]]; 然后
for / in /etc/zsh.d/*.zsh(N); 做
源$ f
DONE
科幻
(N)告诉zsh为该模式设置NULL_GLOB选项。 当没有find匹配的时候,glob会扩展为空string而不是抛出错误。 在zsh中for循环一个空的扩展什么都不做,这是我们在这里想要的行为。
parsingls是一个坏主意 。
相反,您可以使用shell通配符来获取文件列表:
if [[ -d "/etc/zsh.d" ]]; then for f in /etc/zsh.d/*.zsh; do source $f done fi
至于redirect,我不确定它的目的是什么,但是如果你使用这个方法,那么这个shell可能会抛出错误,而不是ls ,所以在for循环done之后执行redirect。
我希望你明白,几乎所有的语法在zsh中工作得很好?
# Check dir exists then that there are files in it (silently!) # If there are no .zsh files in /etc/zsh.d then an empty argument # is passed to for, which then simply skips the loop if [ -d /etc/zsh.d ]; then for file in $(find /etc/zsh.d/ -name '*.zsh'); do source $file done fi
我试图尽可能快,因为你在login脚本。
这应该适用于整个Bourne家族。