How do I store "just" the file names and their associated extension into an array or list in a "bash" script? In a way that every filename is stored in a separate element WITHOUT other file information that ls spits out like the date created or the permission levels...
Asked
Active
Viewed 887 times
-1
-
1I prefer this answer https://stackoverflow.com/questions/18884992/how-do-i-assign-ls-to-an-array-in-linux-bash – Osred Brockhoist Apr 01 '19 at 01:41
-
4[Don't parse `ls`](https://mywiki.wooledge.org/ParsingLs), just use something like `files=(*)`. – Gordon Davisson Apr 01 '19 at 04:04
2 Answers
1
I like to do:
filelist=`ls -1 /somedir/`
and then iterate over $filelist.
ls -1 will only show the filenames without any of the other attributes.
Ken S.
- 133
- 6
-
Thanks for the great input. How do you translate that in bash? Sorry I'm new to linux and trying to learn my way through it. – Sam Apr 01 '19 at 02:28
1
Something like this:
root@myserver-1-00:~# filelist=($(ls))
root@myserver-1-00:~# echo $filelist
Desktop
root@myserver-1-00:~# echo ${filelist[0]}
Desktop
root@myserver-1-00:~# echo ${filelist[1]}
Documents
root@myserver-1-00:~# echo ${filelist[2]}
Downloads
variable=($(yourcommand)) --> makes the output to be assigned as an array
abhishek phukan
- 654
- 5
- 14