In bash
, how can I print the first n
elements of a list?
For example, the first 10 files in this list:
FILES=$(ls)
An addition to the answer of "Ayman Hourieh" and "Shawn Chin", in case it is needed for something else than content of a directory.
In newer version of bash you can use mapfile to store the directory in an array. See help mapfile
mapfile -t files_in_dir < <( ls )
If you want it completely in bash use printf "%s\n" *
instead of ls
, or just replace ls
with any other command you need.
Now you can access the array as usual and get the data you need.
First element:
${files_in_dir[0]}
Last element (do not forget space after ":" ):
${files_in_dir[@]: -1}
Range e.g. from 10 to 20:
${files_in_dir[@]:10:20}
Attention for large directories, this is way more memory consuming than the other solutions.