I have to run some programs in bash script.Sometimes program may not give result.
#!/bin/sh
for k in $( seq 1 20)
do
echo -n ${k}' ' >> 2.txt
./s${k}>>2.txt & sleep 5
done
My ideal result like this:
1 result001
2 result002
3
4 result004
But after run my code,the result is
1 result001
2 result002
3 4 result004
So my problem is how to check a program run successful in bash script?Thank you!
This should work for you.
#!/bin/bash
for k in {1..20}
do
result=$(./s${k} & sleep 5)
printf "%b %b\n" $k $result >> 2.txt
done
The following output was given when testing this script:
1 result1
2 result2
3
4 result4
Try to use wait
http://en.wikipedia.org/wiki/Wait_%28command%29
wait [n]
where n is the pid or job ID of a currently executing background process (job). If n is not given, the command waits until all jobs known to the invoking shell have terminated.
wait normally returns the exit status of the last job which terminated. It may also return 127 in the event that n specifies a non-existent job or zero if there were no jobs to wait for.
Because wait needs to be aware of the job table of the current shell execution environment, it is usually implemented as a shell builtin.
Just add wait
after this line
./s${k}>>2.txt & sleep 5
wait
In case the process can deadlock - another option is timeout
timeout -s 9 5 ./s${k}>>2.txt # Waits 5 seconds and then kill the process
You could call the jobs sequentially and use timeout
to limit execution time:
#!/bin/sh
for k in $( seq 1 20)
do
echo -n ${k}' ' >> 2.txt
timeout -k 8 5 ./s${k}>>2.txt
done
This will terminate each job with the TERM
signal (allowing cleanup via signal handlers to run) after 5 seconds and, if unsuccessful, with the KILL
signal after 8 seconds.
However from your shell's perspective, no parallel processes are involved and you don't need to solve any concurrency problems.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.