The Bash variable SHLVL is another option.
Whether this simple solution works for you depends on whether or not your two calling methods have different shell depths. When they do, this method is quick and easy!
I was just trying to solve this problem myself tonight, and didn't know how to do it in Bash. So I compared the outputs of "env" in both use cases using diff. I saw that SHLVL was set to 2 from the command line, and 3 when run from another shell script.
# Avoid clearing the screen when called from another script
if [ ! "$SHLVL" -gt "2" ]; then
clear
fi
I used ! -gt 2 ("not greater than 2") to ensure my check wouldn't break in the case of a nested script-within-a-script situation, where the SHLVL increases to 4 and beyond.
If you check SHLVL on the actual command line (and from custom functions or aliases on the command line), the SHLVL variable will be set to 1. From non-interactive shells, such as cronjobs, I'm not sure if SHLVL will be set to 0 or 1.
Note: Posting on an old topic because it still shows up on web searches in 2024, and this simple solution hasn't been mentioned here. I'm not sure if Bash added SHLVL, or if it was a feature of Unix sh.
-o filename
) would be ideal - easy, but explicit. – Mratask add blah blah
and not worry where I typed it. If I need to type a slew of redirects or options everytime, I won't use it because it's not convenient enough. – Ferriage