0

A while ago I wrote this loop in a zsh script, and now I don't remember what it does, and I need to convert this script to run in sh.

for f in ${HOME}/.dotfiles/files/*(N) ${HOME}/.dotfiles/files/.*(N); do symlink_prompt $(basename $f) done 

Can someone help me understand what this does, and how I can duplicate it in sh syntax?

2
  • Hi perhaps for f in .* *; do symlink_prompt $(basename $f) ; done Commented Jul 2, 2019 at 20:41
  • 1
    @MichaelDorst : Unfortunately, Posix shell does not have an equivalent to the (N) modifier of zsh. You can leave out the modifier, but if you have no matches for the pattern, you will get an message on stderr, and you will need to test inside the loop for the existence of the file. Also, in Posix shell you need to write $(basename "$f"), just in case f contains white space. Commented Jul 3, 2019 at 7:07

1 Answer 1

2

The glob qualifier (N) causes the pattern to disappear entirely should it fail to match any files. There is no directly equivalent in POSIX shell; instead, you should simply check if f actually exists and continue if it does not. (If the pattern fails to match any files, f takes the literal pattern as its value instead.)

for f in "$HOME"/.dotfiles/files/* "$HOME"/.dotfiles/files/.*; do [ -e "$f" ] || continue symlink_prompt "$(basename "$f")" done 

If you are actually using bash, you can set the nullglob option instead.

shopt -s nullglob for f in "$HOME"/.dotfiles/files/* "$HOME"/.dotfiles/files/.*; do symlink_prompt "$(basename "$f")" done 
Sign up to request clarification or add additional context in comments.

4 Comments

I love that [ -e "$f" ] || continue line. The fact that && and || as control structures is idiomatic in shell scripting is just crazy to me.
Well, that's what they are. They aren't boolean operators, and shell doesn't have boolean values, so they're free for other uses.
Turns out this isn't perfectly equivalent, because "$HOME"/.dotfiles/files/.* will match . and ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.