Bash Array Bulk Operations
Manipulate indexed arrays safely with quoted expansion, slice and search builtins, and mapfile ingestion so filenames with spaces survive round trips.
Code
#!/usr/bin/env bash
set -euo pipefail
# mapfile 把命令输出按行灌进数组(含空格的文件名不碎裂)
mapfile -t files < <(printf '%s\n' 'report Q1.csv' 'notes.md' 'data set.json')
echo "count: ${#files[@]}"
# 追加与删除
files+=('todo.txt')
for i in "${!files[@]}"; do
[[ "${files[$i]}" == notes.md ]] && unset 'files[i]'
done
# 切片与搜索
echo "first two: ${files[@]:0:2}"
# 安全展开:"$@" 语义的 "${arr[@]}" 逐元素引用
for f in "${files[@]}"; do
printf 'processing <%s>\n' "$f"
doneInside the snippet
set -euo pipefail puts the script into strict mode: it stops on the first failing command, treats unset variables as errors, and fails a pipeline if any stage fails.
The work is delegated to mapfile, chained so each stage’s output feeds the next.
The core lines of the flow
for i in "${!files[@]}"; do
[[ "${files[$i]}" == notes.md ]] && unset 'files[i]'
for f in "${files[@]}"; do
printf 'processing <%s>\n' "$f"
Interactive Tools for This Topic
Bitwise Operations CalculatorCompute AND, OR, XOR, NOT, and shifts on 32-bit unsigned operands with binary, hex, and signed decimal views.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does the script stop on the first error?
- Yes — `set -euo pipefail` aborts on the first failing command, treats unset variables as errors, and fails the whole pipeline if any stage fails. Nothing continues half-broken.
- Which external commands does the script rely on?
- `mapfile` must be available on the PATH environment variable; everything else is shell built-in syntax.
Report a problem with this exampleOpens a pre-filled issue on GitHub.