Yuan Wen Yuan Wen - 4 months ago 12
Bash Question

How to recover when stuck by executing wrong shell commands?

I'm using Git Bash 2.9.0-64-bit in win7 64bit.
Here is my shell code

function sum1_x(){
a=$1
while [ $a -ge 1 ]; do
sum=$[$sum + $a]
a=$[$a - 1]
done

echo $sum
}

sum $1


In Git Bash,my type history is as follows:


wen@PC-WEN MINGW64 /d/git/ (dev)

$sh sum1_x.sh

exit

:q

quit

quit()

exit()


After I typed
sh sum1_x.sh
,I can no longer execute any shell command.I tried many commands as shows.I know there are bugs in my script,but how can I get back to execute shell script facing this kind of problems? Nothing can I do now.

Answer

You have several problems with your script:

  1. you have function sum1_x but you are calling sum $1
  2. You didn't check that input value exists, because of it you stuck in infinite loop

Here is the corrected script with check that input argument is exists:

function sum1_x(){
a=$1
while [ $a -ge 1 ]; do
  sum=$[$sum + $a]
  a=$[$a - 1]
done

echo $sum
}

if [ -z "$1" ]; then  # check that input parameter is exists
echo "No input"
else
sum1_x $1
fi

How to stop program:

  1. Ctrl + 'c'
  2. Open new mingw and find pid of the progrman via ps -aux | grep "sum1_x.sh"
    and then use kill pid to kill the program
Comments