0

I am trying to write a nested bash loop here. In every directory in my working directory, I have text files and I want to create a new directory called `nucleotide frequency' in each directory if I read the first text file. Here is what I tried, but it doesn't work.

for d in */ ; do
    echo "My Directories: " ${d}
    for f in $d/*.txt; do
        echo "My File: " ${f}
        if [f = 1]
        then
            mkdir $d/nucleotide_frequency
        fi
    done
done
Nguyen Cong
  • 174
  • 1
  • 13
MAPK
  • 5,635
  • 4
  • 37
  • 88
  • Note that `mydir/myfile.txt` will never match `1`. If the file contains a single number you want to read, you can use `read value < "$f"; echo "The value was $value"` – that other guy Mar 28 '19 at 22:42
  • @thatotherguy The duplicate you marked is completely different – MAPK Mar 28 '19 at 22:54
  • I've reopened the question, but I don't understand how it's different. Is `bash: [f: command not found` or `dash: 5: [f: not found` not the error you're getting? Can you please edit the post and add the errors? – that other guy Mar 28 '19 at 23:01
  • 1
    How about running your script through http://shellcheck.net/, fixing the problems it tells you about, and THEN asking for help with the parts that are still giving you trouble? – ghoti Mar 28 '19 at 23:28

1 Answers1

0

You were close. What was missing was your check for the text file.

This:

if [f = 1]

Is looking to see if the function or program f is equal to the number 1.

The bash built-in if function has a flag -s to check to see if file exists and has a size greater than zero.

for d in */
do
  echo "My Directories: ${d}"
  for f in "${d}"/*.txt
  do
    echo "My File: ${f}"
    # Let's make sure that the file exists and is not empty
    if [[ -s "${f}" ]]
    then
      mkdir "${d}"/nucleotide_frequency 2>/dev/null
      break
    fi
  done
done

Introduction to if

  • This is not working for me: `My Directories: mitochondria/ My File: mitochondria//*.txt bash: [: missing `]' My Directories: retrotransposons/ My File: retrotransposons//*.txt bash: [: missing `]' My Directories: rRNA/ My File: rRNA//*.txt bash: [: missing `]'` – MAPK Mar 28 '19 at 23:04
  • Jason, you'll need a space before the close-square-bracket on the `if` line, and it's generally recommended to use `[[` instead of `[` if POSIX portability isn't a factor. Also, it's a good idea to recommend that folks quote their variables and use `printf` instead of `echo` whenever possible. While it isn't always required, it's easier just to do it across the board than to understand where and how it's not an improvement. :) (And I'm looking forward to upvoting your first answer!) – ghoti Mar 28 '19 at 23:31
  • Ah, thanks. I’ve edited the code to include a space after the square bracket. That thing gets me man. – Jason Adams Mar 29 '19 at 00:02