Return file descriptor from Bash function Return file descriptor from Bash function shell shell

Return file descriptor from Bash function


You don't need to return any kind of special reference type. Assuming bash 4.1 or newer, you can let the shell automatically assign an available FD number, and then do an indirect assignment to store that in a caller-specified variable:

# accept variable name to store FD in as an argumentql_connect() {  local _qlfd _fd_var=$1  exec {_qlfd}<>"/dev/tcp/localhost/$(<~/.quicklock/server-port)" || return  printf -v "$_fd_var" %s "$_qlfd"}if ql_connect qlfd; then  echo "hello" >&$qlfdfi

With bash 3, by contrast, it's better to let the user explicitly assign a FD:

ql_connect() {  local eval_str  printf -v eval_str \    'exec %q<>%q\n' "$fd_num" "/dev/tcp/localhost/$(<~/.quicklock/server-port)"  eval "$eval_str"}if ql_connect 3; then  echo "hello" >&3fi