BinRoot
BinRoot

Reputation: 694

Pipe arguments into bash from terminal

Let's say I have the script convertToPNG.sh

convert $1 output.png

I can call it via the terminal $ converToPNG img.jpg.

But what if instead all I have is the string "convert $1 output.png", and I want to execute it by passing in an argument all in one line?

I don't want to save the string as a file and then run the script with the argument passed in. Isn't there a simpler way to pipe an argument to substitute in the $1,

Upvotes: 0

Views: 106

Answers (2)

unconditional
unconditional

Reputation: 7646

That's a strange use case, but if you really want that you could define your function and pass it the param all in one line:

$ myconvert(){ convert "$1" output.png; }; myconvert whatever.gif

whatever.gif being the file you want to convert.

Upvotes: 1

GHugo
GHugo

Reputation: 2654

You should use eval. It takes a string and executes it. For example:

eval "convert $1 output.png"

But take cares, it executes any string, so you should carefully validate your $1 argument, otherwise anyone may execute any command in your system.

Edit: if what you want is to replace every $1 by img.gif, try the following (single quopt:

bash -c 'convert $1 output.png' 'ignore' 'img.gif'

Upvotes: 1

Related Questions