Skip to content

Commit 2197a52

Browse files
authored
Passing command arguments using heredoc syntax
1 parent 73dd150 commit 2197a52

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

zsh/argument-heredoc.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Passing command arguments using heredoc syntax
2+
3+
This trick works for both Bash and zsh.
4+
5+
I wanted to pass the following as an argument to the sqlite-utils CLI tool:
6+
7+
```
8+
insert into documents select
9+
substr(s3_ocr_etag, 2, 8) as id,
10+
key as title,
11+
key as path,
12+
replace(s3_ocr_etag, '"', '') as etag
13+
from
14+
index2.ocr_jobs;
15+
```
16+
17+
Problem: this contains both single AND double quotes, which makes string escaping a tiny bit tricky.
18+
19+
Solution: use heredoc syntax:
20+
```
21+
sqlite-utils sfms.db --attach index2 index.db "$(cat <<EOF
22+
insert into documents select
23+
substr(s3_ocr_etag, 2, 8) as id,
24+
key as title,
25+
key as path,
26+
replace(s3_ocr_etag, '"', '') as etag
27+
from
28+
index2.ocr_jobs;
29+
EOF
30+
)"
31+
```
32+
Breaking that apart: the main trick here is to use `cat <<EOF ... EOF` to wrap the literal chunk of text:
33+
```
34+
$(cat <<EOF
35+
insert into documents select
36+
substr(s3_ocr_etag, 2, 8) as id,
37+
key as title,
38+
key as path,
39+
replace(s3_ocr_etag, '"', '') as etag
40+
from
41+
index2.ocr_jobs;
42+
EOF
43+
)
44+
```
45+
Then to pass it as an argument to the `sqlite-utils` command use `"$(cat ...)"` - the double quotes around that ensure that tokens in that input are not treated as separate arguments by zsh/bash.

0 commit comments

Comments
 (0)