让我们假设我正在运行这样的东西:
jq -nr --arg target /tmp \
'(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"' \
| sh
Run Code Online (Sandbox Code Playgroud)
一切都很好,除非我忘记传递变量$target:
$ jq -nr '(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"'
jq: error: $target is not defined at <top-level>, line 1:
(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"
jq: 1 compile error
Run Code Online (Sandbox Code Playgroud)
我怎样才能捕捉到这个并使用默认值?
我试过了:
$target?($target)?try $target catch null$target? // null但是好像是解析时的错误,运行时显然是抓不到的。我错过了任何动态语法吗?
我发现可以在 中找到命令行参数$ARGS.name,但有两个缺点:
小智 -1
假设您需要使用 jq 做一些比在文本文件上写入“Hello World”更有用的事情。我提出以下建议,也许我们可以从耶稣那里学习一些编程技巧:
“凯撒的归凯撒,上帝的归上帝”
假设Caesar是bash shell,God是jq,bash适合工作和测试文件、目录和环境变量的存在,jq适合处理json格式的信息。
#!/bin/bash
dest_folder=$1
#if param1 is not given, then the default is /tmp:
if [ -z $dest_folder ]; then dest_folder=/tmp ; fi
echo destination folder: $dest_folder
#check if destination folder exists
if [ ! -d $dest_folder ]
then
echo "_err_ folder not found"
exit 1
fi
jq -nr --arg target $dest_folder '(["echo","Hello, world"]|@sh)+">\($target)/sample.txt"' | sh
#if the file is succesfully created, return 0, if not return 1
if [ -e "$dest_folder/sample.txt" ]
then
echo "_suc_ file was created ok"
exit 0
else
echo "_err_ when creating file"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)
现在您可以将此脚本作为一个步骤包含在更复杂的批处理中,因为它与 Linux 风格一致,成功时返回 0。