1

The ash shell in busybox doesn't seem to implement any of the standard ways to get the filename that's being sourced. For instance:

testo:

#!/usr/bin/env -S busybox ash
echo hello whorl
echo using source
source ./sourceme
echo using .
. ./sourceme

sourceme:

echo underscore $_
echo bs $BASH_SOURCE
echo zero $0
# ./testo 
hello whorl
using source
underscore ./testo
bs
zero ./testo
using .
underscore ./testo
bs
zero ./testo

I need something to put in sourceme that will get its own name/path.

1 Answer 1

1

This excellent answer contains a very clever way to accomplish this. I've adapted their solution here - insert this line into sourceme:

echo lsof `lsof -p $$ -Fn | tail -n1 | sed 's!^[^/]*!!g'``

And you get:

lsof /absolute/path/to/sourceme

Note: since we're talking about busybox here, this is an implementation of the above using busybox's lsof:

lsof | grep '^'$$ | tail -n1 | awk '{print $3}'

Note: if anyone finds a way to do this using some builtin mechanism from busybox ash, post an answer and I'll change the accepted answer to yours.

6
  • Have you considered getting the list of open files direct from procfs (which is to say, from a readlink in the directory /proc/self/fd)? I'm not sure what value, if any, lsof is adding here. (Also, asking lsof to NUL-delimit output but then immediately converting away from NULs is just weird). Commented Feb 11, 2022 at 18:10
  • ...ahh, the "why" is support for MacOS (which doesn't have /proc/self/fd). If you aren't on a Mac, though, I'd probably avoid that hairball of a command. Commented Feb 11, 2022 at 18:11
  • @CharlesDuffy I hadn't considered that. Honestly I didn't even really look at what was inside the lsof line, but now I sort of want to implement the lighter weight version with procfs. I'll update when I get it. Thanks! Commented Feb 11, 2022 at 18:31
  • @CharlesDuffy Couldn't get a procfs solution to work myself (not using a Mac). But I was able to clean up the command a little. I see why the original author of the line was using null as the field termination character, but it isn't necessary. Updating the answer with slightly streamlined version of the one-liner. Commented Feb 11, 2022 at 18:46
  • So, the place I erred in giving you advice was suggesting /proc/self/fd instead of /proc/$$/fd -- the former will give you the file descriptors open in readlink or ls or whatever other tool you have the shell starting; the latter gives you the file descriptors open in the shell itself. Commented Feb 11, 2022 at 18:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.