I am just getting started with bash scripting and I was trying to write a simple script where I can list all the files with a certain extension using a bash script. I mostly code in Python or Matlab so I am very used to setting the address of the folder and using the cd function to change path to that folder and getting the list of the files in that folder. I was trying to do that with bash and I am not what I am doing wrong. For example, I am trying to list all the subfolders in a folder with the following address "/home/user012/Desktop/folder2Start"

So far i have tried

cd "/home/user012/Desktop/folder2Start"

and it hasn't done much when I run it from terminal.

How would I cd into it and list its folders?

Any help would be greatly appreciated..

  • What sort of errors you get when you try to cd ? Is the path correct ? Are there any special characters that should be in any folder names ? – Sergiy Kolodyazhnyy Jul 24 at 18:01
up vote 1 down vote accepted

You should use something like:

ls -l -d /home/user012/Desktop/folder2Start/*/
  • */ looks for directories
  • -d says do not print the content of those directories.

This is a typical use case for shell globbing (pathname expansion):

/home/user012/Desktop/folder2Start/*/

Here i have used */ which will match any file (*) under /home/user012/Desktop/folder2Start/, that is a directory (trailing /).

If you want to operate on these later, better put the result of expansion in an array (works in a similar manner to Python list, both are 0-indexed too):

directories=( /home/user012/Desktop/folder2Start/*/ )

then you can reference the array and it's elements using usual array manipulation operators.

OTOH, if you want the list, use echo/printf/ls -- whatever suits you the best:

printf '%s\n' /home/user012/Desktop/folder2Start/*/
echo /home/user012/Desktop/folder2Start/*/
ls -ld /home/user012/Desktop/folder2Start/*/

for any directory name with embedded newline, lookout for tailing / as name ending marker.

  • Thanks a lot for the response. I am trying to do something along the lines of using directories=( /home/user012/Desktop/folder2Start/*/ ) However, when i use this way, i get the following error bash: /testBash.sh: No such file or directory I want to store the folders and then see if they have any subfolders which might have files of my interest – sanster9292 Aug 6 '17 at 4:59

U can list that "folder2Start" file by issuing :

ls -la /home/user012/Desktop/folder2Start

Maybe I'm too late but the question still active, I hope it can be useful for you.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.