bash function - determine if running as a script or tty - bash

Say I have a bash function:
run_stuff(){
if is_in_script; then
exit 1
fi
return 1;
}
basically, if I am running it in a script:
$ ./my-script.sh
then I want to exit with 1, but if I am running it directly in the terminal:
$ run_stuff
then I want to return 1 (o/w my terminal window will close)
what is the best way to check this cross-platform?

You can use $0.
echo $0 when run in my (bash) terminal returns -bash.
echo $0 in a script with no #! run with bash test.sh returns test.sh
echo $0 in a script with #!/bin/bash run as ./test.sh returns ./test.sh

It's not bullet proof, but you can check whether the current shell is interactive:
is_in_script() {
[[ $- == *i* ]]
}
However, I would just make run_stuff always return, and if a script should exit when the command reports failure, it can do run_stuff || exit rather than leaving this behavior up to the function itself.

Related

Abort bash script if git pull fails [duplicate]

I have a Bash shell script that invokes a number of commands.
I would like to have the shell script automatically exit with a return value of 1 if any of the commands return a non-zero value.
Is this possible without explicitly checking the result of each command?
For example,
dosomething1
if [[ $? -ne 0 ]]; then
exit 1
fi
dosomething2
if [[ $? -ne 0 ]]; then
exit 1
fi
Add this to the beginning of the script:
set -e
This will cause the shell to exit immediately if a simple command exits with a nonzero exit value. A simple command is any command not part of an if, while, or until test, or part of an && or || list.
See the bash manual on the "set" internal command for more details.
It's really annoying to have a script stubbornly continue when something fails in the middle and breaks assumptions for the rest of the script. I personally start almost all portable shell scripts with set -e.
If I'm working with bash specifically, I'll start with
set -Eeuo pipefail
This covers more error handling in a similar fashion. I consider these as sane defaults for new bash programs. Refer to the bash manual for more information on what these options do.
To add to the accepted answer:
Bear in mind that set -e sometimes is not enough, specially if you have pipes.
For example, suppose you have this script
#!/bin/bash
set -e
./configure > configure.log
make
... which works as expected: an error in configure aborts the execution.
Tomorrow you make a seemingly trivial change:
#!/bin/bash
set -e
./configure | tee configure.log
make
... and now it does not work. This is explained here, and a workaround (Bash only) is provided:
#!/bin/bash
set -e
set -o pipefail
./configure | tee configure.log
make
The if statements in your example are unnecessary. Just do it like this:
dosomething1 || exit 1
If you take Ville Laurikari's advice and use set -e then for some commands you may need to use this:
dosomething || true
The || true will make the command pipeline have a true return value even if the command fails so the the -e option will not kill the script.
If you have cleanup you need to do on exit, you can also use 'trap' with the pseudo-signal ERR. This works the same way as trapping INT or any other signal; bash throws ERR if any command exits with a nonzero value:
# Create the trap with
# trap COMMAND SIGNAME [SIGNAME2 SIGNAME3...]
trap "rm -f /tmp/$MYTMPFILE; exit 1" ERR INT TERM
command1
command2
command3
# Partially turn off the trap.
trap - ERR
# Now a control-C will still cause cleanup, but
# a nonzero exit code won't:
ps aux | grep blahblahblah
Or, especially if you're using "set -e", you could trap EXIT; your trap will then be executed when the script exits for any reason, including a normal end, interrupts, an exit caused by the -e option, etc.
The $? variable is rarely needed. The pseudo-idiom command; if [ $? -eq 0 ]; then X; fi should always be written as if command; then X; fi.
The cases where $? is required is when it needs to be checked against multiple values:
command
case $? in
(0) X;;
(1) Y;;
(2) Z;;
esac
or when $? needs to be reused or otherwise manipulated:
if command; then
echo "command successful" >&2
else
ret=$?
echo "command failed with exit code $ret" >&2
exit $ret
fi
Run it with -e or set -e at the top.
Also look at set -u.
On error, the below script will print a RED error message and exit.
Put this at the top of your bash script:
# BASH error handling:
# exit on command failure
set -e
# keep track of the last executed command
trap 'LAST_COMMAND=$CURRENT_COMMAND; CURRENT_COMMAND=$BASH_COMMAND' DEBUG
# on error: print the failed command
trap 'ERROR_CODE=$?; FAILED_COMMAND=$LAST_COMMAND; tput setaf 1; echo "ERROR: command \"$FAILED_COMMAND\" failed with exit code $ERROR_CODE"; put sgr0;' ERR INT TERM
An expression like
dosomething1 && dosomething2 && dosomething3
will stop processing when one of the commands returns with a non-zero value. For example, the following command will never print "done":
cat nosuchfile && echo "done"
echo $?
1
#!/bin/bash -e
should suffice.
I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:
[[ `cmd` ]] && echo success_else_silence
Which is the same as cmd || exit errcode as someone showed.
For example, I want to make sure a partition is unmounted if mounted:
[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

How to stop execution in script which may have been sourced or directly executed

If my script gets sourced with
. ./my_script.sh
source ./my_script.sh
then to stop execution in the script, I would use return.
If my script is directly executed with
./my_script.sh
bash ./my_script.sh
then I'd insert an exit.
If I don't know whether the user will source it or directly execute it, how can I cleanly stop the script without killing the terminal it was called from?
Preferably, the code snippet should be able to terminate the script even if it were placed inside one of the script's functions.
Try the following:
ec=0 # determine the desired exit code
return $ec 2>/dev/null || exit $ec
return will succeed if the script is being sourced, otherwise exit will kick in. The 2>/dev/null suppresses the error message in case the script is not sourced.
The net effect is that the script will terminate with the desired exit / return code, regardless of whether it was sourced or not.
Update: The OP wants to be able to exit the script from inside a function within the script.
The only way I can think of is to place all of your script's code in a subshell and call exit from inside the functions inside that subshell; then place the return 2>/dev/null || exit command after the subshell (as the only statement outside the subshell):
#!/usr/bin/env bash
( # subshell to place all code in
foo() {
exit 1 # exit the subshell
}
foo # invoke the function
)
# Terminate script with exit code from subshell.
ec=$?; return $ec 2>/dev/null || exit $ec
Here's one way to find out which method was used to invoke the script.
if [[ "$0" == "bash" ]]; then
echo "source 'file' was used"
else
echo "bash 'file' was used"
fi
Update, In response to comment by #mklement0:
If your script is named my_script.sh, you can use
b=$(basename "$0")
if [[ "$b" == "my_script.sh" ]]; then
echo "bash 'file' was used"
else
echo "source 'file' was used"
fi

How to check the current shell and change it to bash via script?

#!/bin/bash
if [ ! -f readexportfile ]; then
echo "readexportfile does not exist"
exit 0
fi
The above is part of my script. When the current shell is /bin/csh my script fails with the following error:
If: Expression Syntax
Then: Command not found
If I run bash and then run my script, it runs fine(as expected).
So the question is: If there is any way that myscript can change the current shell and then interpretate rest of the code.
PS: If i keep bash in my script, it changes the current shell and rest of the code in script doesn't get executed.
The other replies are correct, however, to answer your question, this should do the trick:
[[ $(basename $SHELL) = 'bash' ]] || exec /bin/bash
The exec builtin replaces the current shell with the given command (in this case, /bin/bash).
You can use SHEBANG(#!) to overcome your issue.
In your code you are already using she-bang but make sure it is first and foremost line.
$ cat test.sh
#!/bin/bash
if [ ! -f readexportfile ]; then
echo "readexportfile does not exist"
exit 0
else
echo "No File"
fi
$ ./test.sh
readexportfile does not exist
$ echo $SHELL
/bin/tcsh
In the above code even though I am using CSH that code executed as we mentioned shebang in the code. In case if there is no shebang then it will take the help of shell in which you are already logged in.
In you case you also check the location of bash interpreter using
$ which bash
or
$ cat /etc/shells |grep bash

Getting exit code of last shell command in another script

I am trying to beef up my notify script. The way the script works is that I put it behind a long running shell command and then all sorts of notifications get invoked after the long running script finished.
For example:
sleep 100; my_notify
It would be nice to get the exit code of the long running script. The problem is that calling my_notify creates a new process that does not have access to the $? variable.
Compare:
~ $: ls nonexisting_file; echo "exit code: $?"; echo "PPID: $PPID"
ls: nonexisting_file: No such file or directory
exit code: 1
PPID: 6203
vs.
~ $: ls nonexisting_file; my_notify
ls: nonexisting_file: No such file or directory
exit code: 0
PPID: 6205
The my_notify script has the following in it:
#!/bin/sh
echo "exit code: $?"
echo "PPID: $PPID"
I am looking for a way to get the exit code of the previous command without changing the structure of the command too much. I am aware of the fact that if I change it to work more like time, e.g. my_notify longrunning_command... my problem would be solved, but I actually like that I can tack it at the end of a command and I fear complications of this second solution.
Can this be done or is it fundamentally incompatible with the way that shells work?
My shell is Z shell (zsh), but I would like it to work with Bash as well.
You'd really need to use a shell function in order to accomplish that. For a simple script like that it should be pretty easy to have it working in both zsh and bash. Just place the following in a file:
my_notify() {
echo "exit code: $?"
echo "PPID: $PPID"
}
Then source that file from your shell startup files. Although since that would be run from within your interactive shell, you may want to use $$ rather than $PPID.
It is incompatible. $? only exists within the current shell; if you want it available in subprocesses then you must copy it to an environment variable.
The alternative is to write a shell function that uses it in some way instead.
One method to implement this could be to use EOF tag and a master script which will create your my_notify script.
#!/bin/bash
if [ -f my_notify ] ; then
rm -rf my_notify
fi
if [ -f my_temp ] ; then
rm -rf my_temp
fi
retval=`ls non_existent_file &> /dev/null ; echo $?`
ppid=$PPID
echo "retval=$retval"
echo "ppid=$ppid"
cat >> my_notify << 'EOF'
#!/bin/bash
echo "exit code: $retval"
echo " PPID =$ppid"
EOF
sh my_notify
You can refine this script for your purpose.

korn vs bash exit code

I have the following problem:
I have some test scripts that previously were run with ksh (from MKS Toolkit)
The scripts will need to remain unmodified (not a single character will be changed).
I will use bash (from Mingw/Msys) to run these scripts.
The problem is in the following:
This works fine in KornShell (ksh) but doesn't work in bash:
typeset -i errorCode
errorCode=10
exit errorCode
I need to modify the script like this (note the $ sign):
typeset -i errorCode
errorCode=10
exit $errorCode
Is there a way to make the code to be compilable with bash without making the chnage I mentioned?
Thanks
Assuming that your code is in a file named foo.sh, you can wrap it with process substitution. For example:
bash <(sed 's/errorCode$/$&/' foo.sh)
Bash interprets the modified code as read from the file descriptor, and the exit status of the subshell is set as expected.
$ echo $?
10
you can also do this before executing the ksh script in bash
#!/bin/bash
exit ()
{
unset -f exit
if expr match "$1" '^[-|+|0-9|.][.0-9]*$' &> /dev/null ; then
exit "$1"
fi
exit
}
source ./the_ksh_script
to override exit.
This example is compatible with the original code, i.e. gives exit code of 0.
Second example
exit () {
unset -f exit
eval rc2=\$$1
rc1=$1
for rc in "$rc1" "$rc2"
do
if expr match "$rc" '^[-|+|0-9|.][.0-9]*$' &> /dev/null ; then
exit "$rc"
fi
done
exit
}
source ./the_ksh_script
will produce the exit code 10, probably what the original script intends.

Resources