Bash Parameter Expansion - get part of directory path

620 views Asked by At

Lets say I have this variable

FILE=/data/tenant/dummy/TEST/logs/2020-02-03_16.20-LSTRM.log

I'm trying to get the name of the 4th sub directory, in this example TEST

job=${FILE%/*/*}   # This gives me /data/tenant/dummy/TEST

Then

name=${job##*/} 

This give me exactly what I want - Test

However when I try to use this in for loop like this:

for FILE in "/data/tenant/dummy/*/logs/*$year-*"; do
  job=${FILE%/*/*}
  echo $job    # /data/tenant/dummy/TEST(and few other directories, so far so good)
  name=${job##*/} 
  echo $name  
done

The result of echo $name shows the list of files in my current directory I'm in instead of TEST

1

There are 1 answers

2
markp-fuso On BEST ANSWER

Main issue is the double quotes groups all files into a single long string:

for FILE in "/data/tenant/dummy/*/logs/*$year-*"

You can see this if you do something like:

for FILE in "/data/tenant/dummy/*/logs/*$year-*"
do
    echo "+++++++++++++++++++"
    echo "${FILE}"
done

This should print ++++++++++++++ once followed by a single line with a long list of file names.

To process the files individually remove the double quotes, eg:

for FILE in /data/tenant/dummy/*/logs/*$year-*

It's also good practice to wrap individual variable references in double quotes, eg:

job="${FILE%/*/*}"
echo "$job"
name="${job##*/}"
echo "$name"