1
function projectopen {
    local di_files=(*.xcworkspace */*.xcworkspace *.xcodeproj */*.xcodeproj)

    # open first exsit file
    ls -d -f -1 $di_files  2>/dev/null \
    | head -1 \
    | xargs open
}

I write a shell function to quick open xcworkspace in terminal. But when I declare di_files as a local var, then the function is broken, and log

projectopen:1: number expected

I use zsh on Mac OS. Why this happen and how to fix it?

  • how did you declare di_files? you shouldn't have any problems making your array variable local to the function – the_velour_fog Nov 25 '16 at 8:41
  • I update the function.@the_velour_fog – Karl Nov 25 '16 at 10:21
  • then I suspect there is something else going on and its probably that ls command. I would try removing or commenting out the ls command. then re-run your projectopen function defintion. I think you should find its ok. if so, then your could address the ls command – the_velour_fog Nov 25 '16 at 10:24
3

In older versions of zsh you cannot initialise an array with local (or typeset/declare) like that, you need to separate it, e.g.

local -a di_files # explicit array
di_files=( ... )

The feature to permit declaration and array assignment together was added in v5.1.

I believe the error you see is because zsh is treating the initialisation as scalar and () as a glob qualifier.

You can also probably replace your elaborate pipeline with the simpler

open "${di_files[1]}"

Finally, including handling for no matching files:

function projectopen {
  setopt local_options nullglob
  local di_files=(*.xcworkspace */*.xcworkspace *.xcodeproj */*.xcodeproj)

  # open first existing file
  [ -n "${di_files[1]}" ] && open "${di_files[1]}"
}

With the nullglob option each glob expansion which matches no files is replaced with an empty string (I suspect you may have nonomatch set, a related option).

  • Great answer. But ls also excluded none existed files for me, any improve to your suggestions. – Karl Nov 25 '16 at 15:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.