I'm trying to ensure that my script only executes when it's running in a terminal window. If it's not in a terminal, I want it to sleep for 3 seconds and then exit. I've looked into using the $SHLVL variable for this, but I'm not sure if it's the best method or if there are more reliable alternatives. My rough script idea is something like:
If $SHLVL > 1 then
Echo running in terminal
Echo continuing
Elif $SHLVL <= 1 then
Sleep 3
Exit
Else
Echo how is this even possible?
Fi
I'm currently on a road trip, away from my PC, but I wanted to jot down a general test script to try once I get home.
2 Answers
Using the $SHLVL variable can be a helpful trick, as it typically indicates whether you're in a nested shell or an interactive terminal. However, it's not foolproof. A more reliable method would be checking if the script is connected to a terminal explicitly using the `tty` command. If `tty` returns a valid terminal device, then you can be sure the script is running in a terminal session.
The problem with $SHLVL is that it can sometimes be misleading. It might indicate a terminal session, but if you're running scripts from an IDE or other tools, it can still return a value that confuses matters. Using `tty` helps clarify if you're really in a terminal. Just check it by executing `if [ -t 1 ]; then ...` to confirm you're in an interactive terminal. It's a clean way to avoid issues!
Thanks for the tip! I'll implement that check in my script instead.

Got it! So, just using `tty` gives a more accurate check, right? I'll revise my script to include that.