1

I am currently writing some scripts to be utilized in an alpine linux container, and I want this be as lightweight as possible so I am refraining from installing bash. I plan on sourcing a shell script, but don't want it to execute when I source it.

I understand that if I was using bash I could easily do the following:

#!/usr/bin/env bash
set -e

main(){
    echo "something witty"
}

if [[ "$_" -eq "$0" ]]; then
    main
fi

But I am drawing a blank for sh.

Here is a demo of the lack of ability to us $_ in sh for an attempt at simular functionality:

/ # ./test.sh
+ echo 

/ # cat test.sh 
#!/bin/sh

set -ex

echo "$_"
/ # echo "$_"
test.sh
/ #

Any recommendations?

Robert J
  • 840
  • 10
  • 20
  • 1
    Honestly, I'd look at why you are sourcing it in the first place if you don't want it to actually do anything, rather than making it detect if it was sourced. – chepner Dec 10 '18 at 16:42
  • @chepner that is a good point. I was really only sourcing a script to use an 8 line function again. I have since just copied the function to my second script, but I am more curious than anything else now. – Robert J Dec 12 '18 at 16:42
  • Does this answer your question? [How to detect if a script is being sourced](https://stackoverflow.com/questions/2683279/how-to-detect-if-a-script-is-being-sourced) – Andrey Kaipov Mar 18 '21 at 02:26

0 Answers0