0

I'm trying to write a bash script that recursively goes through files in a directory, writing the file's name and hexdump to a file. My current script:

#/bin/sh
touch hexdump.txt
for filename in logical/*; do
    echo "$filename"
    "$filename" >> hexdump.txt
    hd /logical/"$filename" >> hexdump.txt
done

The current output is:

logical/*
./hexadecimalExtraction.sh: line 5: logical/*: No such file or directory
hd: /logical/logical/*: No such file or directory

How do i get it to interpret "logical/*" as the list of files within "logical" directory and not the filename itself???

M.Perry
  • 1
  • 1
  • Looks like your `logical/` directory is empty. What does `printf '%s\n' logical/*` say? – Petr Skocik Nov 05 '18 at 17:13
  • Where is this "logical" directory"? `logical/*` will look for it (and files inside it) under the current working directory, but with `/logical`, the leading "/" will make it look at the top level of the filesystem instead. The difference matters. – Gordon Davisson Nov 05 '18 at 17:57
  • add a `[[ -f "$filename" ]] || continue` after the do, maybe? – Paul Hodges Nov 05 '18 at 19:42
  • likewise, if you find `logical/fileX` your call to `hd` is going to try to operate on `/logical/logical/fileX`. Is that what you intended? – Paul Hodges Nov 05 '18 at 19:44

3 Answers3

0
"$filename" >> hexdump.txt

should probably be removed

Otherwise you are trying to run the filename itself.

Also you are looking for files in logical subdirectory in the current directory, but the trying to look in /logical/

lostbard
  • 5,065
  • 1
  • 15
  • 17
0

You can't recurse with for filename in logical/*. In order to recurse, you have to use find. To make find visit only files, not directories, use find -type f. I don't know hd, but you probably want

find tutorials -type f | while read i; do
    echo $i >> hexdump.txt
    hd $i >> hexdump.txt
done
Frank Neblung
  • 3,047
  • 17
  • 34
0

You're looking for the ** glob operator.

shopt -s globstar nullglob
for filename in logical/**/*; do
    echo "$filename"
    hd "$filename"
done >> hexdump.txt

filename will contain the full name of the matched files, which already includes the directory logical and any sub directories.

chepner
  • 497,756
  • 71
  • 530
  • 681