Skip to content

Instantly share code, notes, and snippets.

@CMCDragonkai
Last active August 18, 2017 16:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CMCDragonkai/6c3716fa6445f7ca448d to your computer and use it in GitHub Desktop.
Save CMCDragonkai/6c3716fa6445f7ca448d to your computer and use it in GitHub Desktop.
CLI: Get a free unused file descriptor
#!/usr/bin/env sh
# this works in sh, ash, bash, zsh
# and works in Linux and Cygwin and Busybox
# probably works in Mac too
# remember process subtitution is not POSIX
# comm would normally require --nocheck-order but busybox comm doesn't, so we just send error messages to /dev/null
# min_fd -> max_fd -> number_of_fds_to_return
get_free_fd () {
seq "$1" "$2" > /tmp/free_fd
echo -n /proc/$$/fd/[0-9]* | tr ' ' '\0' | xargs -0 -I '{}' basename '{}' | sort -n > /tmp/used_fd
free_fd="$(comm -23 /tmp/free_fd /tmp/used_fd 2>/dev/null | head -n "$3")"
rm /tmp/free_fd && rm /tmp/used_fd
printf "$free_fd"
[ -n "$free_fd" ] && return 0 || return 1
}
# use it like:
get_free_fd 0 $(ulimit -n) 1
# it will return a file descriptor or return nothing at all
# you can test for an available file descriptor using `test -n`
# if you're in bash 4.0 or latest ZSH, there's an easier ways to do this
# see: http://stackoverflow.com/a/17030546/582917
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment