1

I'm trying to find a files with name and copy it into one text file using bash scripting

What I need to do is I want to add one more command to it so that it is iterate through these files and execute gdb command for each file and print those gdb details into same file which created before

what I'm doing is

#!bin/bash

fpath=/home/filepath

find $fpath -name "core.*" -exec ls -larh {} ; > $fpath/deleted_files.txt while read line; do gdb ./exec $line done; < $fpath/deleted_files.txt

It should read the only file name like below

gdb ./exec core.123

But Its reading the files like below and giving error

gdb ./exec -rw-rw-r-- 1 home home 0 2022-12-06 13:59 /home/filepath/core.123
gdb : unrecognised option '-rw-rw-r--'

How can i give only filename into that command and paste it into txt file.

Angela
  • 11

1 Answers1

1
  1. If you don't want long format listing in the output file, then don't use ls's -l option.

  2. Do you really need the deleted_files.txt file? If not, if the only reason you're creating it is so you can iterate over each filename, you could just run find . -name 'core.*' -exec gdb /exec {} \;.

  3. If you need the listing as well, then maybe use something like one of the following:

# first make sure $fpath will be inherited by
# child processes (find and bash -c)
export fpath

find . -name 'core.*' -exec bash -c ' for corefile; do printf "%s\n" "$corefile" >> "$fpath/deleted_files.txt" gdb /exec "$corefile" done ' bash {} +

or just run find twice:

find . -name 'core.*' > "$fpath/deleted_files.txt"
find . -name 'core.*' -exec gdb /exec {} \;

Or use an array so you only have to run find once:

# read find's output into array corefiles with mapfile.  use NUL as
# the filename separator.
mapfile -d '' -t corefiles < <(find . -name 'core.*' -print0)

output the array to $fpath/deleted_files.txt, with a newline

between each filename.

printf '%s\n' "${corefiles[@]}" > "$fpath/deleted_files.txt"

iterate over the array and run gbd on each corefile.

for cf in "${corefiles[@]}" ; do gdb /exec "$cf" done


BTW, remember to quote your variables. See Why does my shell script choke on whitespace or other special characters? and $VAR vs ${VAR} and to quote or not to quote

Kusalananda
  • 333,661
cas
  • 78,579