Showing posts with label shell. Show all posts
Showing posts with label shell. Show all posts

Thursday, March 4, 2010

Redirecting or error output to variable in shell

Spent couple of painful hours trying to do that. And eventually, here is the code which will output standard output into the file and error into the variable:

var=`(ls -l > ./file.txt) 2>&1`

bloody shell...

Tuesday, February 23, 2010

Kill all child processes from shell script

Small and simple script. Creates Ctrl-C trap and kills all it's child processes in it. Nice to have when your script has many child processes which execution have to be stopped when main script is interrupted by Ctrl-C or other signal.


kill_child_processes() {
isTopmost=$1
curPid=$2
childPids=`ps -o pid --no-headers --ppid ${curPid}`
for childPid in $childPids
do
kill_child_processes 0 $childPid
done
if [ $isTopmost -eq 0 ]; then
kill -9 $curPid 2> /dev/null
fi
}

# Ctrl-C trap. Catches INT signal
trap "kill_child_processes 1 $$; exit 0" INT

for (( i = 0 ; i <= 5; i++ ))
do
# do something...
sleep 10 &
done

wait