Luke H.’s Post

View profile for Luke H., graphic

IT Administrator | Security+, Network+, Linux+, A+

I just realized I haven't posted a Linux tip in quite a while, so here's one that's a bit more advanced than my other ones. CAUTION this is pretty nerdy: The [mapfile] command is a seldom used builtin BASH command that is more often used in scripts than directly in the terminal emulator itself. What it can do: It allows you to create a new array variable from standard input (stdin) with each entry terminated by a delimiter of your choosing (or newline [NUL] by default.) Did I lose you? It's OK, let's just keep going. Let's say you have a file called "names.txt" with the following three lines in it: Adam Paul Robert Let's create an array variable called "people" using each line from the names.txt file: mapfile people < names.txt Here we have created an array with three entries. Each entry is given its own number in ascending order starting from zero. So 0 is "Adam", 1 is "Paul" and 2 is "Robert". Understand? Zero is a number too. So what can we do with this? We can call any given line from the array and use it however we like. Let's simply echo the first entry from the variable to display it on stdout: # echo ${people[0]} Adam We can also display all of the entries at once by using the @ symbol rather than a specific array assignment: # echo ${people[@]} Adam Paul Robert Now, if you're an advanced BASH user you might be asking why not just use a "read loop". Sure, that would be a more portable option but creating an array in this fashion is much faster. Final thought: You don't have to use a file to create an array with mapfile. You may use anything from stdin with any delimiter you like. Use your imagination. Now tell me what this one does and you win the internet for today: mapfile -t parts < <(lsblk | grep part) #linux #nerdystuff #programming #scripting #BASHscript

Kiumarz Hashemi

Linux Specialist | Linux Enthusiast

1mo

Love it. Keep making these please.

To view or add a comment, sign in

Explore topics