[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Is there a way to get the output of a function without an extra bash
From: |
Koichi Murase |
Subject: |
Re: Is there a way to get the output of a function without an extra bash process? |
Date: |
Tue, 12 May 2020 03:15:46 +0900 |
2020-05-11 6:20 Peng Yu <address@hidden>:
>
> Hi,
>
> $(fun) by default will always use a new bash process. This is wasteful
> in certain cases. In there a way to use the existing bash process
> (without using a temp file)? Thanks.
Another solution with a shell function.
$ cat a.sh
#!/bin/bash
_ble_base_run=$(mktemp -d)
trap -- 'rm -rf "$_ble_base_run"' EXIT
_ble_util_assign_base=$_ble_base_run/$$.ble_util_assign.tmp
_ble_util_assign_level=0
function ble/util/assign {
local _ble_local_tmp=$_ble_util_assign_base.$((_ble_util_assign_level++))
builtin eval "$2" >| "$_ble_local_tmp"
local _ble_local_ret=$? _ble_local_arr=
((_ble_util_assign_level--))
mapfile -t _ble_local_arr < "$_ble_local_tmp"
IFS=$'\n' eval "$1=\"\${_ble_local_arr[*]}\""
return "$_ble_local_ret"
}
# sample
function f { echo "$BASHPID"; }
pid=$(f)
echo "command subst : $BASHPID,$pid"
ble/util/assign pid f
echo "ble/util/assign: $BASHPID,$pid"
$ bash a.sh
command subst : 39173,39175
ble/util/assign: 39173,39173
Actually, this function `ble/util/assign' is maintained as one of the
most important utilities in my script for more than five years and
tested well.
https://github.com/akinomyoga/ble.sh/blob/54769337/src/util.sh#L1414-L1446
Maybe you don't like it because it internally uses temporary files,
but you do not have to care about the handling of temporary files as
the shell function takes care of them. If you do not want to cause
disk access, you can create temporary files/directories on in-memory
filesystems (tmpfs) such as /dev/shm or /tmp. Even if the system does
not mount in-memory filesystems, filesystem access is much faster than
fork & exec.
--
Koichi
Re: Is there a way to get the output of a function without an extra bash process?, Chris F.A. Johnson, 2020/05/10