简体   繁体   English

从终端将参数传递到bash

[英]Pipe arguments into bash from terminal

Let's say I have the script convertToPNG.sh 假设我有脚本convertToPNG.sh

convert $1 output.png

I can call it via the terminal $ converToPNG img.jpg . 我可以通过终端$ 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? 但是,如果我只有字符串"convert $1 output.png" ,而我想通过在一行中全部传递一个参数来执行它,该怎么办?

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 , 我不想将字符串另存为文件,然后使用传入的参数运行脚本。没有一种更简单的方法来将参数传递给$1

You should use eval . 您应该使用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. 但是请注意,它会执行任何字符串,因此您应该仔细验证$1参数,否则任何人都可以在系统中执行任何命令。

Edit: if what you want is to replace every $1 by img.gif, try the following (single quopt: 编辑:如果您要用img.gif替换每个$1 ,请尝试以下操作(单个quopt:

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

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. whatever.gif是要转换的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM