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..
Best Answer
This is a typical use case for shell globbing (pathname expansion):
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):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:for any directory name with embedded newline, lookout for tailing
/
as name ending marker.