OrenIshShalom
OrenIshShalom

Reputation: 7162

execute gdb from bash loop quits immediately

I have a simple bash script that runs some program 3 times in a loop (/home/oren/Downloads/users.txt file has a single line)

#!/bin/bash
#######################
# Loop over all users #
#######################
while IFS='' read -r username
do
    for answer in {1..3};
    do
        ##############################################
        # Only perform check if both files exist ... #
        ##############################################
        if [ -f /home/oren/Downloads/someFile.txt ] && [ -f /home/oren/Downloads/anotherFile.txt ];
        then
            gdb --args /home/oren/Downloads/MMM/example PPP DDD 
        fi
    done
done < /home/oren/Downloads/users.txt

Here is /home/oren/Downloads/users.txt file:

cat /home/oren/Downloads/users.txt

And the answer is:

OrenIshShalom

When I remove the gdb --args prefix the program works fine (that is, it divides by zero like it should) Here is the program:

#include <stdio.h>

int main(int argc, char **argv)
{
    int i=0;
    if (argc > 1)
    {
        i = (i+argc)/(argc-3);
    }
}

However when I add the gdb --args, gdb quits immediately:

...
(gdb) quit

What's going on here? Thanks!

EDIT:

When I remove the outer loop gdb works fine ... but I would very much prefer to keep this loop as everything in the script is built on it

Upvotes: 0

Views: 385

Answers (1)

pynexj
pynexj

Reputation: 20768

The whole while loop (including read and gdb) would share the stdin which is /home/oren/Downloads/users.txt so your gdb would also consume data from /home/oren/Downloads/users.txt. gdb exits immediately because it quickly consumes all data and sees EOF.

See following example:

[STEP 109] # cat file
line 1
line 2
line 3
[STEP 110] # cat foo.sh
while read line; do
    gdb /bin/ls
done < file
[STEP 111] # bash foo.sh
GNU gdb (Debian 7.12-6) 7.12.0.20161007-git
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
[...]
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from /bin/ls...(no debugging symbols found)...done.
(gdb) Undefined command: "line".  Try "help".
(gdb) Undefined command: "line".  Try "help".
(gdb) quit
[STEP 112] #

For your case you can load the file /home/oren/Downloads/users.txt to an array and go through it:

usernames=()
nusers=0
while IFS='' read -r username; do
    usernames[nusers++]=$username
done < /home/oren/Downloads/users.txt

for username in "${usernames[@]}"; do
    ...

    gdb ...

    ...
done

Upvotes: 1

Related Questions