4 ms·
The way one typically accomplishes this in bash is the following since the $() construct spawns a subshell. #!/bin/bash fun() { res="resul
by Spivak 7y ago
The way one typically accomplishes this in bash is the following since the $() construct spawns a subshell.
#!/bin/bash
fun() {
res="result"
}
fun && echo "$res"
The same strace snippet.
openat(AT_FDCWD, "./test.sh", O_RDONLY) = 3
stat("./test.sh", {st_mode=S_IFREG|0755, st_size=53, ...}) = 0
ioctl(3, TCGETS, 0x7ffd65c6d890) = -1 ENOTTY (Inappropriate ioctl for device)
lseek(3, 0, SEEK_CUR) = 0
read(3, "#!/bin/bash\n\nfun() {\n res=\"resu"..., 80) = 53
lseek(3, 0, SEEK_SET) = 0
prlimit64(0, RLIMIT_NOFILE, NULL, {rlim_cur=1024, rlim_max=512*1024}) = 0
fcntl(255, F_GETFD) = -1 EBADF (Bad file descriptor)
dup2(3, 255) = 255
close(3) = 0
fcntl(255, F_SETFD, FD_CLOEXEC) = 0
fcntl(255, F_GETFL) = 0x8000 (flags O_RDONLY|O_LARGEFILE)
fstat(255, {st_mode=S_IFREG|0755, st_size=53, ...}) = 0
lseek(255, 0, SEEK_CUR) = 0
read(255, "#!/bin/bash\n\nfun() {\n res=\"resu"..., 53) = 53
fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(0x88, 0x2), ...}) = 0
write(1, "result\n", 7result
) = 7
read(255, "", 53) = 0
rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
exit_group(0) = ?
If you want use the old magics to return values like the built-ins then it's a little uglier but a lot cleaner.
#!/bin/bash
fun() {
eval $1=\""result"\"
}
fun res && echo $res
- kazinator 7y agoAssignment to hard-coded global variable is not a return mechanism, and generally a nonstarter. It's not a viable approach for generally returning strings out shell functions everywhere in a codebase as a matter of habit. Use of eval: still slow, because the shell eval re-processes input from the character level and up. eval should be generally avoided as much as possible in shell programming. Careless use of eval can introduce security holes (piece of untrusted datum gets evaled as an expression). You really need to have your black belt in "shell escaping karate". Producing output and capturing with command substitution is the primary idiom for getting text out of a shell function. It has no visible side effect. The rebinding of standard output is scoped to the process substitution (and is confined to the child process, in fact), and the creation of the temporary process and pipe, expensive as they might be, are invisible to the program semantics. > The way one typically accomplishes this in bash In summary, what you propose here is not only vanishingly atypical, but also bad coding practice.
- Spivak 7y ago> In summary, what you propose here is not only vanishingly atypical, but also bad coding practice. What I'm describing has been SOP in bash for twenty years. You can program in a more modern style and replace some uses of eval with ${!indirect_references}, declare, and associative arrays but eval is still in wide use today. Search through /etc for eval with grep and you'll return plenty of results in the wild. For example the eval in my previous post could be rewritten as the following declare -g "$1"="result" but this form, although safer, is the less common usage. Assigning to global variables or passing in a variable name to get the return value is just how bash works. See $MAPFILE $OPTIND $OPTARG for examples of the former and read as an example of the latter.
- LukeShu 7y agoThat [declare -g] is bad too, because it means you can't use it to set a local variable (see my sibling comment about dynamic scoping), which is surprising and confusing to the caller. While I agree with the parent that the whole thing is disgusting, I also recognize that it's a valid optimization technique, and it's sometimes necessary. So, if you do go down that route, I'd encourage you to do it as printf -v "$1" '%s' "$result"
- LukeShu 7y agoWithout disagreeing with the essence of what you said: > Assignment to hard-coded global variable ... Because Bash is dynamically-scoped, it's not necessarily global; it could be scoped to the calling function. For example: setit() { myvar=bar } myfunc() { local myvar setit echo myfunc $myvar # will print: myfunc bar } myvar=foo myfunc # will print: myfunc bar echo global $myvar # will print: global foo
- kazinator 7y agoMost shell programmers do not know what "dynamic scope" is, lacking a Lisp background. Those familiar with lexical languages like C or Java will naively expect "local" to be lexical. Unlike in dynamically scoped Lisps, in shell programming there isn't any widely recognized and applied naming convention to avoid accidental name capture due to dynamic scope (binding a variable, not knowing that a function which is then used accesses that as a global). POSIX has no "local", and so makes no recommendation in this regard, nor sets any naming precedent for users programs to follow. It is more concerned with the separation between system variables (named with ALL_CAPS) and user variables (not so named). Put these two together and you have a recipe for bugs.