2

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

returns

zsh: parse error near `200'

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

JdeBP
  • 68,745

2 Answers2

7

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

llua
  • 6,900
3

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
)
thrig
  • 34,938
  • 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 09 '21 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 01 '22 at 21:17