In bash
, how can I print the first n
elements of a list?
For example, the first 10 files in this list:
FILES=$(ls)
UPDATE: I forgot to say that I want to print the elements on one line, just like when you print the whole list with echo $FILES
.
Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.
To get the first element (10) from the array, we can use the subscript [ ] syntax by passing an index 0 . In bash arrays are zero-indexed, so the first element index is 0 .
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.
FILES=(*)
echo "${FILES[@]:0:10}"
Should work correctly even if there are spaces in filenames.
FILES=$(ls)
creates a string variable. FILES=(*)
creates an array. See this page for more examples on using arrays in bash. (thanks lhunath)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With