본문으로 건너뛰기
0%
약 1분 (293 단어) ko

Working with Bash Arrays

Categories TechSavvy Bash
Tags #TechSavvy #ProgrammingLanguage #Bash

array(list)

In Bash, you can represent arrays using parentheses. The delimiter inside is the space bar - pretty simple!

$ cat array_ex.sh
#!/bin/bash
lists=("a" b "c")
echo ${lists[1]}
echo ${lists[0]}
echo ${lists[3]}
echo ${lists[2]}
$ sh array_ex.sh
b
a

c

Notice how lists[3] returns empty since we only have 3 elements (indices 0, 1, 2). Bash won’t complain - it just gives you nothing, which is actually quite handy for conditional checks.

Slicing is also supported, as shown in the example below:

lists=("V0.1.0" "V1.0.0")
echo "[1] : "${lists[1]}
echo "[0] : "${lists[0]}
echo "[3] : "${lists[3]}
echo "[-1] : "${lists[-1]}

selected=${lists[-1]}
echo "selected : "$selected

The negative indexing [-1] is pretty cool - it gives you the last element, just like in Python! This makes it super easy to grab the most recent version or the last item without having to calculate the array length.

Pro tip: When working with arrays in Bash, always remember that they’re zero-indexed and space-delimited. If you need comma-separated values, you’ll need to handle that separately or use a different approach.

Appendix. References

Share this article

Found this helpful? Share it with your network

Join the Discussion

Share your thoughts and connect with other readers

댓글

GitHub 계정으로 로그인하여 댓글을 남겨보세요. 건설적인 의견과 질문을 환영합니다!

댓글을 불러오는 중...