Home > Software design >  bash if and then statements both run
bash if and then statements both run

Time:04-22

I'm running this in bash and even though there is a .txt file it prints out "no new folders to create" in the terminal. Am I missing something?

FILES=cluster-02/*/*

for f in $FILES
do        
        if [[ $f == *."txt" ]] 
        then
                cat $f | xargs mkdir -p
        else
                echo "No new folders to create"
        fi
done;

CodePudding user response:

You're looping over multiple files, so the first result may trigger the if and the second can show the else.

You could save the wildcard result in an array, check if there's something in it, and loop if so:

shopt -s nullglob

FILES=( foo/* )

if (( ${#FILES[@]} )); then
    for f in "${FILES[@]}"; do
        if [[ $f == *."txt" ]]; then
            echo $f
        fi
    done
else
    echo "No new folders to create"
fi

CodePudding user response:

As mentioned in the first comment, the behaviour is indeed as you might expect from your script: you run through all files, text files and other ones. In case your file is a text file, you perform the if-case and in case your file is another type of file, you perform the else-case.

In order to solve this, you might decide not to take the other files into account (only handle text files), I think you might do this as follows:

FILES=cluster-02/*/*.txt

CodePudding user response:

#!/usr/bin/env bash

# Create an array containing a list of files
# This is safer to avoid issues with files having special characters such
# as spaces, glob-characters, or other characters that might be cumbersome
# Note: if no files are found, the array contains a single element with the
#       string "cluster-02/*/*"
file_list=( cluster-02/*/* )

# loop over the content of the file list
# ensure to quote the list to avoid the same pitfalls as above
for _file in "${file_list[@]}"
do
   [ "${_file%.txt}" == "${_file}" ] && continue # skip, not a txt
   [ -f "${_file}" ]                 || continue # check if the file exists
   [ -r "${_file}" ]                 || continue # check if the file is readable
   [ -s "${_file}" ]                 || continue # check if the file is empty
   < "${_file}" xargs mkdir -p --    # add -- to avoid issues with entries starting with -
   _c=1
done;
[ "${_c}" ] || echo "No new folders to create"
  • Related