ycliper

Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
Скачать

How to Store lsblk Command Output in a Bash Associative Array

Store output of lsblk command key=value into associative array in bash

bash

awk

sed

Автор: vlogize

Загружено: 2025-05-28

Просмотров: 1

Описание: Learn how to process `lsblk` command output and store it in a structured associative array in Bash for easy access and manipulation.
---
This video is based on the question https://stackoverflow.com/q/66274650/ asked by the user 'Hrishikesh Kadam' ( https://stackoverflow.com/u/3302026/ ) and on the answer https://stackoverflow.com/a/66281625/ provided by the user 'markp-fuso' ( https://stackoverflow.com/u/7366100/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.

Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: Store output of lsblk command key=value into associative array in bash

Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.

If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Mastering Bash: Storing lsblk Command Output in an Associative Array

When working with Linux systems, the lsblk command is incredibly useful for listing block devices and their properties. However, you might want to extract specific pieces of information and store them in a more structured format, such as an associative array in Bash. This allows for straightforward access to attributes like mount points, labels, and UUIDs. In this guide, we'll walk through the steps to achieve that.

The Challenge

Suppose you have the following output from the lsblk command:

[[See Video to Reveal this Text or Code Snippet]]

You want to store this data in an associative array named partition so that:

partition[MOUNTPOINT] contains /media/user/GParted Live

partition[LABEL] contains GParted Live

partition[UUID] contains xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

So how do we convert this raw output into a structured array? Let’s dive into the solution using a well-organized Bash script.

Step-by-Step Solution

1. Prepare Your Input Data

For this example, we'll assume we have the lsblk output stored in a file called lsblk.out. The contents look like this:

[[See Video to Reveal this Text or Code Snippet]]

2. Using sed to Format the Output

To start, we need to format the output properly. The goal is to transform the single line of lsblk output into separate lines for each key-value pair. We can achieve this using sed:

[[See Video to Reveal this Text or Code Snippet]]

This command uses a regular expression to match each key-value pair and outputs them on separate lines.

3. Reading and Storing in Associative Array

With the formatted output ready, we can then read each line into our associative array. Here’s how you can do it:

[[See Video to Reveal this Text or Code Snippet]]

4. Verifying the Results

Now that we’ve populated the array, let's verify that our associative array contains the expected values:

[[See Video to Reveal this Text or Code Snippet]]

This will print the contents of the partition array, allowing you to confirm everything is stored correctly.

5. Displaying the Contents

To display the values stored in the array neatly, you can loop through the keys like this:

[[See Video to Reveal this Text or Code Snippet]]

This will output each key along with its corresponding value:

[[See Video to Reveal this Text or Code Snippet]]

6. Stripping Double Quotes (Optional)

If you’d like to remove the double quotes surrounding the values, you can modify the read operation like this:

[[See Video to Reveal this Text or Code Snippet]]

This replaces double quotes with nothing, giving you clean values.

7. Using lsblk Directly

You can also feed the lsblk command directly without saving its output to a file:

[[See Video to Reveal this Text or Code Snippet]]

Conclusion

By following the above steps, you now have the necessary knowledge to take raw output from the lsblk command and store it in a structured associative array for easier access and manipulation in your Bash scripts. Associative arrays provide a powerful way to manage data in a recognizable and accessible format, making your scripts cleaner and more efficient.

Feel free to test the provided code snippets in your own environment to see how they work in action. Happy scripting!

Не удается загрузить Youtube-плеер. Проверьте блокировку Youtube в вашей сети.
Повторяем попытку...
How to Store lsblk Command Output in a Bash Associative Array

Поделиться в:

Доступные форматы для скачивания:

Скачать видео

  • Информация по загрузке:

Скачать аудио

Похожие видео

10 | How to Create Arrays in PHP | Indexed & Associative Arrays | 2023 | PHP Course for Beginners

10 | How to Create Arrays in PHP | Indexed & Associative Arrays | 2023 | PHP Course for Beginners

Top 15 Shell Scripting Interview Questions for DevOps | Shell Scripting Interview Prep | DevOps prep

Top 15 Shell Scripting Interview Questions for DevOps | Shell Scripting Interview Prep | DevOps prep

Learn C++ With Me #9 - Arrays

Learn C++ With Me #9 - Arrays

13 Linux Commands Every Engineer Should Know (Real-World Example)

13 Linux Commands Every Engineer Should Know (Real-World Example)

Quickly Apply for Grants with ChatGPT and AI

Quickly Apply for Grants with ChatGPT and AI

threading vs multiprocessing in python

threading vs multiprocessing in python

Что такое TCP/IP: Объясняем на пальцах

Что такое TCP/IP: Объясняем на пальцах

ШУЛЬМАН: На фронт отправят всех подряд. ФСБ возродит ГУЛАГ. Ускорение репрессий. Борьба с мигрантами

ШУЛЬМАН: На фронт отправят всех подряд. ФСБ возродит ГУЛАГ. Ускорение репрессий. Борьба с мигрантами

Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional

Arrays in Bash Explained in 7 Minutes! - Indexed, Associative, and Nested / Multi-Dimensional

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

LLM и GPT - как работают большие языковые модели? Визуальное введение в трансформеры

© 2025 ycliper. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]