Skip to content

Commit 2a92e68

Browse files
committed
Add a new API @quote
1 parent 0ec007a commit 2a92e68

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed

README-cn.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,20 @@ Bach 测试框架中提供的 API 都是以 `@` 开头的。
753753

754754
用于在标准控制台输出内容,每个参数输出一行。
755755

756+
### @quote
757+
758+
用于在标准控制台输出经过 shell 转义的内容,每个参数输出一行。当需要将包含空格或特殊字符的参数传递给 `xargs` 等命令时非常有用。
759+
760+
例子:
761+
762+
@quote "hello world" "foo bar"
763+
# 输出:
764+
# hello\ world
765+
# foo\ bar
766+
767+
# 与 xargs 配合使用
768+
@quote "file with spaces.txt" "another file.txt" | xargs -I{} -- rm {}
769+
756770
### @trap
757771

758772
执行真正的内置 `trap` 命令。

README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,20 @@ Output content to the stderr console, one line per parameter.
714714

715715
Output content to the stdout console, one line per parameter.
716716

717+
### @quote
718+
719+
Output shell-quoted content to the stdout console, one line per parameter. This is useful when passing arguments that may contain spaces or special characters to commands like `xargs`.
720+
721+
Example:
722+
723+
@quote "hello world" "foo bar"
724+
# Output:
725+
# hello\ world
726+
# foo\ bar
727+
728+
# Using with xargs
729+
@quote "file with spaces.txt" "another file.txt" | xargs -I{} -- rm {}
730+
717731
## Learn Bash Programming with Bach
718732

719733
test-learn-bash-no-double-quote-star() {

bach.sh

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -682,6 +682,11 @@ function @stdout() {
682682
}
683683
builtin export -f @stdout
684684

685+
function @quote() {
686+
builtin printf '%q\n' "$@"
687+
}
688+
builtin export -f @quote
689+
685690
function @load_function() {
686691
local file="${1:?script filename}"
687692
local func="${2:?function name}"

tests/bach-testing-framework.test.sh

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,34 @@ test-mock-@stdout-include-space-assert() {
154154
}
155155

156156

157+
test-@quote-typical() {
158+
@quote abc 123
159+
}
160+
test-@quote-typical-assert() {
161+
@echo abc
162+
@echo 123
163+
}
164+
165+
166+
test-@quote-include-space() {
167+
@quote "abc 123" "def 456"
168+
}
169+
test-@quote-include-space-assert() {
170+
@echo 'abc\ 123'
171+
@echo 'def\ 456'
172+
}
173+
174+
175+
test-@quote-with-special-characters() {
176+
@quote "it's" 'say "hello"' '$HOME'
177+
}
178+
test-@quote-with-special-characters-assert() {
179+
@echo "it\\'s"
180+
@echo 'say\ \"hello\"'
181+
@echo '\$HOME'
182+
}
183+
184+
157185
test-run-a-script() {
158186
@mock load-script === @echo "for param; do @echo \"script.sh - \$param\"; done"
159187

0 commit comments

Comments
 (0)