I am trying to accomplish something that is easy in bash: look for files in a folder and source them if they exist (and do not output if no files exist).
In bourne shells this is how to do it:
if [ -d /etc/profile.d ]; then for f in `ls -1 /etc/profile.d/*.sh 2> /dev/null`; do . $f done fi
I am new to zsh and cannot get the equivalent working. What am I doing wrong?
if [[ -d "/etc/zsh.d" ]]; then for file in (ls -1 /etc/zsh.d/*.zsh 2> /dev/null); do source $file done fi
fail: parse error near '>'
.
I have tried many variations and cannot get it to be as smooth as the sh/bash equivalent. It's as if redirection does not always work within subshells.
After a later email to the zsh users mailing list, I was given the nearly ideal solution to the problem:
The (N) tells zsh to set the NULL_GLOB option for that pattern. When no matches are found, the glob expands to an empty string instead of throwing an error. In zsh a for loop over an empty expansion does nothing, which is the behavior we want here.
Parsing
ls
is a bad idea.Instead you can just use shell globbing to get a list of files:
As for the redirection, I'm not sure what the purpose of it is in your example, but if you use this method then it's the shell that might throw an error, not
ls
, so perform the redirection afterdone
in thefor
loop.I hope you understand that nearly all sh syntax works just fine in zsh?
I've tried to make it as fast as possible, since you're in a login script.
This should work for the whole Bourne family.