i have a question about simple shell script.
this is the source code of rand.sh below
#!/bin/bash
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
exit 1
fi
echo "Everything went accrding to plan"
and i'm going to make a new shell script, let me call it quiz.sh.
quiz.sh should loop until n==42. if n==42, save the stdout("Something went wrong") and stderr("The error was using magic numbers")
and it finally terminated with printing out those stdout,stderr and Total execution count.
here is my quiz.sh
#!/bin/bash
cnt=0
while [[ "${n}" -ne 42 ]]
do
(( cnt = "${cnt}"+1 ))
source ./rand.sh &> error.txt
done
cat error.txt
echo "${cnt}"
but this is not working. because of exit 1 in rand.sh, the program is terminated before executing cat and echo which is at the end two line.
how can i fix it?? please let me know!
I want to make happen cat error.txt and echo "${cnt}" as well
Run the loop in a subshell
(
while something; do
something
exit 1 # exits only from the subshell
done
)
Note: parent shell doesn't access/inherit child process environment. So cnt is going to be empty in parent shell. Transfer it some other way.
(
cnt=0
while ((n != 42)); do
((cnt++))
echo "$cnt" > cntfile.txt
# >& is deprecated
source myrand > error.txt 2>&1
done
)
cnt=$(<cntfile.txt)
cat error.txt
echo "$cnt"
Reference Bash manual command grouping.
As KamilCuk pointed out correctly, you should use $n instead of n.
Furthermore, I personally would add that using source ./rand.sh &> error.txt is kind of weird in this case. If you want to run it as a background process, use:
./rand.sh &> error.txt &
wait $! # $! is the pid
Otherwise, just make a function out of it:
#!/bin/bash
function myrand {
n=$(( RANDOM % 100 ))
if [[ n -eq 42 ]]; then
echo "Something went wrong"
>&2 echo "The error was using magic numbers"
return 1
fi
echo "Everything went accrding to plan"
return 0
}
cnt=0
while [[ "${n}" -ne 42 ]]
do
(( cnt = "${cnt}"+1 ))
myrand() &> error.txt
done
cat error.txt
echo "${cnt}"
p.s. code not tested, but I guess it works.
Related
I have a pretty simple bash script that coordinates running a couple python scripts. What I am having trouble figuring out is why after running the bash script (. bash_script.sh), the terminal hangs. I can't ctrl+c, ctrl+z or do anything except restart the SSH session. All I see is just a blinking cursor. Checking all the log files indicates a 0 status exit code with no errors in the scripts themselves. Running ps aux | grep bash_script.sh does not show any anything running either. Is there anyway to debug this?
#!/bin/bash
exec >> <DIR>/logfile.log 2>&1
script_message () {
status_arg=$1
if [[ $status_arg = "pass" ]]; then
printf "Script Done\n"
printf '=%.0s' {1..50}
printf "\n"
elif [[ $status_arg = "fail" ]]; then
printf "Script Failed\n"
printf '=%.0s' {1..50}
printf "\n"
else
:
fi
}
current_date=$(date '+%Y-%m-%d %H:%M:%S')
day=$(date +%u)
hour=$(date +%H)
printf "RUN DATE: $current_date\n"
# activate virtual env
source /<VENV DIR/bin/activate>
python <PYTHON SCRIPT>.py >> <DIR>/logfile2.log 2>&1
retVal=$?
if [[ $retVal -eq 0 && $day -eq 4 ]]; then
python <PYTHON SCRIPT 2>.py >> <DIR>/logfile3.log 2>&1
script_message pass
elif [[ $retVal -eq 0 ]]; then
script_message pass
else
#:
script_message fail
fi
echo $?
Here is my code:
#!/bin/bash
if [[ $1 = "" ]]; then
exit 0
fi
array=($(cat $1))
let b=${#array[#]}-1
count=0
for i in {1..7}; do
for j in {30..37}; do
for n in {40..47}; do
if [[ $count -gt $b ]]; then
printf '\n'
printf '\e[0m'
exit 1
fi
printf '\e[%s;%s;%sm%-5s' "$i" "$j" "$n" "${array[$count]}"
printf '\e[0m'
let count=$count+1
done
printf '\n'
done
done
#printf '\n'
printf '\e[0m'
exit 0
The problem is that when I start it like this
. color.sh arg
or without argument, it just closes. I know that the reason for that is exit. Is there any way correct my code so I could start a script with dot at start and terminal wouldn't close after execution? I don't want to start it like this: ./script
Replace all exit with return.
return inside a sourced script will even work with exit codes:
$ . <(echo "echo before; return 0; echo after")
before
$ echo $?
0
$ . <(echo "echo before; return 7; echo after")
before
$ echo $?
7
When you use the dot to run a script you are "sourcing" it, which means the interpreter reads and executes all the commands in that script in the context of the current environment without spawning a subshell, as if you had typed each yourself.
That's why if you source it you can set variables in a script that will remain after it has run, whereas running it in a subshell would encapsulate them, and they would go away when the script ends.
Accordingly, if you source a script that hits an exit, it causes the calling environment to exit. Use return as Socowi suggested.
I have a bash script "domain-ssl-status.sh". I need a script with two arguments so that I could run the script in the following way:
./domain-ssl-status.sh cname.domain.com status|unobtained|obtained|error
domainName and status are my 2 arguments
domainName=$1 and status=$2
I have tried creating a status_map using a case statement, but no luck!! I have also seen other hints on here but mine never seems to work. My sql statement includes SELECT * FROM DomainSSL WHERE domainName='cname.domain.com' and I'm still stuck.
A rough pass at a rewrite -
#!/bin/bash
domainName=$1
status=$2
echo "Verifying domain"
case status in
$status) ping -c 1 $domainName || {
echo "Cannot ping $domainName" >&2
exit 1
} ;;
*) echo "Invalid argument '$status'" >&2
exit 1 ;;
esac
sql="SELECT * FROM DomainSSL WHERE domainName='$domainName'"
mssql -f csv -c ~/applications/mssql/mssql.json -q "$sql" # mark here
rc=$?
if (( rc )) # nonzero
then echo "FAIL: rc $rc on [$sql]" >&2
else echo "SUCCESS: $sql"
fi
You might also want to try saving the stdout and stderr for later parsing.
Rewriting from # mark above,
mssql -f csv -c ~/applications/mssql/mssql.json -q "$sql" >ok 2>oops
rc=$?
if (( rc )) # nonzero
then echo -e "FAIL: rc $rc on [$sql]:\n$(<oops)" >&2
case "$(grep SQLSTATE oops)" in
*ER_DUP_KEY*) : code to handle duplicate keys error ;;
# any other errors you choose to handle . . .
*) : code for bailing on errors you don't care to handle ;;
esac
else echo "SUCCESS: $sql"
fi
c.f. the mysql documentation here
This is just a general template. Hope it helps. Feel free to ask for clarification.
I can't get my bash script (a logging file) to detect any other exit code other than 0, so the count for failed commands isn't being incremented, but the successes is incremented regardless of whether the command failed or succeeded.
Here is the code:
#!/bin/bash
#Script for Homework 8
#Created by Greg Kendall on 5/10/2016
file=$$.cmd
signal() {
rm -f $file
echo
echo "User Aborted by Control-C"
exit
}
trap signal 2
i=0
success=0
fail=0
commands=0
read -p "$(pwd)$" "command"
while [ "$command" != 'exit' ]
do
$command
((i++))
echo $i: "$command" >> $file
if [ "$?" -eq 0 ]
then
((success++))
((commands++))
else
((fail++))
((commands++))
fi
read -p "$(pwd)" "command"
done
if [ "$command" == 'exit' ]
then
rm -f $file
echo commands:$commands "(successes:$success, failures:$fail)"
fi
Any help would be greatly appreciated. Thanks!
That's because echo $i: "$command" is succeeding always.
The exit status $? in if [ "$?" -eq 0 ] is actually the exit status of echo, the command that is run immediately before the checking.
So do the test immediate after the command:
$command
if [ "$?" -eq 0 ]
and use echo elsewhere
Or if you prefer you don't need the $? check at all, you can run the command and check status within if alone:
if $command; then .....; else ....; fi
If you do not want to get the STDOUT and STDERR:
if $command &>/dev/null; then .....; else ....; fi
** Note that, as #Charles Duffy mentioned in the comment, you should not run command(s) from variables.
Your code is correctly counting the number of times that the echo $i: "$command" command fails. I presume that you would prefer to count the number of times that $command fails. In that case, replace:
$command
((i++))
echo $i: "$command" >> $file
if [ "$?" -eq 0 ]
With:
$command
code=$?
((i++))
echo $i: "$command" >> $file
if [ "$code" -eq 0 ]
Since $? captures the exit code of the previous command, it should be placed immediately after the command whose code we want to capture.
Improvement
To make sure that the value of $? is captured before any other command is run, Charles Duffy suggests placing the assignment on the same line as the command like so:
$command; code=$?
((i++))
echo $i: "$command" >> $file
if [ "$code" -eq 0 ]
This should make it less likely that any future changes to the code would separate the command from the capture of the value of $?.
I am trying to write a small bash script to monitor the output of RiotShield (a 3rd party player scraper for League of Legends) for crashes. If a keyword is found in the log it should kill the process and restart it.
Here is my bash script as is:
#!/bin/bash
crash[1]="disconnected"
crash[2]="38290209"
while true; do
list=$(tail log.log)
#clear
echo "Reading Log"
echo "========================================"
echo $list
for item in ${list//\\n/ }
do
for index in 1 2
do
c=${crash[index]}
#echo "Crash Word:" $c
if [[ "$c" == *"$item"* ]]; then
echo "RiotShield has crashed."
echo "Killing RiotShield."
kill $(ps aux | grep '[R]iotShield.exe' | awk '{print $2}')
echo "RiotShield killed!"
echo "Clearing log."
echo > log.log
echo "Starting RiotShield"
(mono RiotShield.exe >> log.log &)
fi
done
done
sleep 10
done
My crash array are keywords that I know show in the log when it crashes. I have 38290209 in there only for testing purposes as it is my summoner ID on League of Legends and the moment I preform a search for my Summoner name the ID shows in the log.
The problem is even when disconnected and 38290209 do not show up in the log my
if [[ "$c" == *"$item"* ]]; then
fires, kills the RiotShield process and then relaunches it.
The length of the crash array will grow as I find more keywords for crashes so I cant just do
if [[ "$c" == "*disconnected*" ]]; then
Please and thanks SOF
EDIT:
Adding working code:
#!/bin/bash
crash[1]="disconnected"
crash[2]="error"
while true; do
list=$(tail log.log)
clear
echo "Reading Log"
echo "========================================"
echo $list
for index in 1 2
do
c=${crash[index]}
#echo "Crash Word:" $c
if [[ $list == *$c* ]]; then
echo "RiotShield has crashed."
echo "Crash Flag: " $c
echo "Killing RiotShield."
kill $(ps aux | grep '[R]iotShield.exe' | awk '{print $2}')
echo "RiotShield killed!"
echo "Clearing log."
echo > log.log
echo "Starting RiotShield"
(mono RiotShield.exe >> log.log &)
fi
done
sleep 10
done
I think you have the operands in your expression the wrong way around. It should be:
if [[ $item == *$c* ]]; then
because you want to see if a keyword ($c) is present in the line ($item).
Also, I'm not sure why you need to break the line into items by doing this: ${list//\\n/ }. You can just match the whole line.
Also note that double-quotes are not required within [[.