Employing the mechanism from the answer at https://unix.stackexchange.com/a/274499/5132 in the Z shell:

flock -x 200

echo "test";

) 200>mylockfile2


zsh: parse error near `200'

While in bash it works correctly. What may be the issue here?

2 Answers 2


Bash is the only shell that allows the user to open a fd higher than 9 directly using the normal redirection syntax. so in other shells the command is equivalent to (...) 200 1>mylockfile2, which is a syntax error. posix only mandates supporting 0-9. If you really want to ensure the fd used with the lock isn't already in use, you can use syntax specifically designed to open the next available fd. (foo "$lockfd";...) {lockfd}>file

  • What does foo or lockfd refer to? Is lockfd a special variable? Oct 14, 2018 at 15:52
  • foo is a arbitrary command, lockfd is just a arbitrary variable named used to store the fd number opened by {lockfd}
    – llua
    Oct 15, 2018 at 0:19
  • yash also supports 200> file. rc, es, akanga as well with the >[200] file syntax. Jul 5, 2019 at 18:31

zsh is not bash despite some efforts between the two camps of peeking over the fence and stealing ideas from one another. Also, flock appears to come from util-linux so portability may be limited. A ZSH solution might instead use the zsystem module; this module provides a flock command:

#!/usr/bin/env zsh
zmodload zsh/system
   local lockvar
   touch lockfile
   zsystem flock -f lockvar lockfile
   print >&2 got lock
   sleep 10
   zsystem flock -u $lockvar
   print >&2 end lock
  • Why do you have the parentheses creating a sub shell? I could not think of a case where I would need them, the code seems to work just fine without the parentheses
    – codepoet
    Sep 9, 2021 at 21:55
  • @reportaman from the docs "The lock terminates when the shell process that created the lock exits; it is therefore often convenient to create file locks within subshells, since the lock is automatically released when the subshell exits."
    – Taeram
    Jun 1, 2022 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .