mcocdawc
mcocdawc

Reputation: 1867

Create one line function in zsh

I want to crop several images using my terminal. For this purpose I tried to write this one-line function.

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

But if I write crop_function test.png The help page of convert pops up. If I write:

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

The output is correctly:

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

What am I doing wrong?

===============EDIT================

The reason it did not work was the escaping. This one does work:

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

I have not understood why, because the function with echo correctly substitutes the variables. So if someone could clarify this, I would be very happy.

Upvotes: 0

Views: 1059

Answers (1)

Adam Katz
Adam Katz

Reputation: 16118

Let's take a look at your function:

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

Thanks to your quotes, this passes a single argument to convert representing
$1 -crop 1048x909+436+78 $1.

Here's an illustration:

function test_args { i=1; for arg in "$@"; 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"; }

Run as:

$ 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

Now that we've diagnosed the issue, we can fix the function:

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

Upvotes: 1

Related Questions