Krushna
Krushna

Reputation: 6040

How to get a folder name in linux bash from a directory

There will be directory which will have any number folder and may be files, I just need pick one random folder and need to process it ( move the folders , etc ..) I need process folder one by one. Need to ignore if there is any files.

I am tiring with below code able to get folder name but , seems there some hidden character or some thing which not giving proper output.

PROCESSING_FOLDER_NAME= ls -l /ecom/bin/catalogUpload/input/TNF-EU/ | grep '^d' | cut -d ' ' -f23 | head -1

#PROCESSING_FOLDER_NAME= echo $PROCESSING_FOLDER_NAME | tr -d '\n\r'

#PROCESSING_FOLDER_NAME=${PROCESSING_FOLDER_NAME%$'\n'}

#echo "PROCESSING_FOLDER_NAME is/$PROCESSING_FOLDER_NAME "

echo  "/ecom/bin/catalogUpload/input/TNF-EU/$PROCESSING_FOLDER_NAME/"

output

Thanks_giving_Dec_08
/ecom/bin/catalogUpload/input/TNF-EU//

I am expecting the output should be /ecom/bin/catalogUpload/input/TNF-EU/Thanks_giving_Dec_08/

Here is my bash version.

GNU bash, version 4.2.50(1)-release (powerpc-ibm-aix6.1.2.0)

I mainly need the folder name (not full path) in variable, As the folder name which is processing need be use for emails to notify other, etc.

Upvotes: 1

Views: 1850

Answers (1)

janos
janos

Reputation: 124648

To get a random folder from a list of folders, first put the list of folders in an array:

list=(/ecom/bin/catalogUpload/input/TNF-EU/*/)

Next, get a random index using the $RANDOM variable of the shell, modulo the size of the list:

((index = RANDOM % ${#list[@]}))

Print the value at the selected index:

echo "${list[index]}"

To get just the name of the directory without the full path, you can use the basename command:

basename "${list[index]}"

As for what's wrong with the original script:

  • To store the result of a command in a variable, the syntax is name=$(cmd) instead of name= cmd
  • Do not parse the output of ls, it's not reliable
  • To get directories in a directory, you can use glob patterns like * ending with /, as in the above example */.

Upvotes: 2

Related Questions