2017-10-20 82 views
0

我想用我的终端裁剪几张图像。为此我尝试写这个单行函数。在zsh中创建一行功能

function crop_function { convert "$1 -crop 1048x909+436+78 $1" } 

但是,如果我写crop_function test.png转换的帮助页面弹出。 如果我写:

function crop_function { echo convert "$1 -crop 1048x909+436+78 $1" } 
convert_function test.png 

输出是正确:

convert test.png -crop 1048x909+436+78 test.png 

我在做什么错?

===============编辑================

它不工作的原因是逃逸。 这个人做的工作:

function crop_function { convert $1 -crop 1048x909+436+78 $1 } 

我不明白为什么,因为正确呼应功能替代的变量。所以如果有人能够澄清这一点,我会非常高兴。

+1

尝试运行'转换“test.png -crop 1048x909 + 436 + 78 test.png”'直接。你会得到同样的错误。 – melpomene

+0

啊,当然。非常感谢你! – mcocdawc

+2

问题不在于被替换的变量,而是将空白作为单个参数的一部分传递,而不是分隔多个参数。 – chepner

回答

1

让我们来看看你的函数:

function crop_function { convert "$1 -crop 1048x909+436+78 $1" } 

感谢您的报价,这传递一个参数convert代表
$1 -crop 1048x909+436+78 $1

这里有一个例证:

function test_args { i=1; for arg in "[email protected]"; do echo "$((i++)): $arg"; done; } 
function test_crop_1 { test_args "$1 -crop 1048x909+436+78 $1"; } 
function test_crop_2 { test_args "$1" -crop "1048x909+436+78" "$1"; } 

运行方式:

$ test_args one two three "four five" 
1: one 
2: two 
3: three 
4: four five 

$ test_crop_1 one two 
1: one -crop 1048x909+436+78 one 

$ test_crop_2 one two 
1: one 
2: -crop 
3: 1048x909+436+78 
4: one 

现在我们已经确诊的问题,我们可以修复功能:

function crop_function { convert "$1" -crop "1048x909+436+78" "$1"; } 
+0

非常感谢您的详细解释! – mcocdawc