-
Notifications
You must be signed in to change notification settings - Fork 1
/
largs
executable file
·93 lines (82 loc) · 2.26 KB
/
largs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env bash
#
# Requirements:
# - sed
# - walk-run (included in the bash-stdops project)
#
# Author: James Cherti
# URL: https://github.com/jamescherti/bash-stdops
#
# Description:
# ------------
# This script reads from standard input and executes a command for each line,
# replacing `{}` with the content read from stdin. It expects `{}` to be passed
# as one of the arguments and will fail if `{}` is not provided.
#
# This script is an alternative to xargs.
#
# { echo "file1"; echo "file2"; } | largs ls {}
#
# License:
# --------
# Copyright (C) 2012-2024 James Cherti
#
# Distributed under terms of the GNU General Public License version 3.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
#
set -euf -o pipefail
main() {
local errno=0
if [[ $# -lt 1 ]]; then
echo "Executes a command for each line in the standard input, "
echo "replacing '{}' with the line content."
echo
echo "Usage: $0 <command> [args] {}" >&2
echo
echo "Example:"
echo " { echo 'file1'; echo 'file2'; } | largs ls {}"
exit 1
fi
local cmd
cmd="$1"
if ! command -v "$cmd" &>/dev/null; then
echo "Error: command not found: $cmd" >&2
exit 1
fi
# Set IFS to newline to properly handle lines with spaces
IFS=$'\n'
local line
while read -r line; do
local brackets_found=0
local cmd
cmd=()
for arg in "$@"; do
if [[ $arg = '{}' ]]; then
cmd+=("$line")
brackets_found=1
else
cmd+=("$arg")
fi
done
if [[ $brackets_found -eq 0 ]]; then
echo "Error: the brackets '{}' are required.'" >&2
exit 1
fi
# echo "[RUN]" "${cmd[@]}" >&2
"${cmd[@]}" || errno=1
done
exit "$errno"
}
main "$@"