我如何可以通过使用在Linux中终端命令文件参数,我的bash脚本? [英] How can I pass a file argument to my bash script using a Terminal command in Linux?

查看:121
本文介绍了我如何可以通过使用在Linux中终端命令文件参数,我的bash脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是我怎么能使用在Linux下终端命令传递文件参数到我的bash脚本?
目前我正在试图让在bash一个程序,可以从终端需要一个文件参数,并用它作为我的程序中的变量。比如我运行
myprogram --file = /路径/要/文​​件在终端。

So my question is how can I pass a file argument to my bash script using a Terminal command in Linux? At the moment I'm trying to make a program in bash that can take a file argument from the Terminal and use it as a variable in my program. For example I run myprogram --file=/path/to/file in Terminal.

#!/bin/bash    
File=(the path from the argument)  
externalprogram $File (other parameters)

我如何与我的计划实现这一目标?

How can I achieve this with my program?

推荐答案

这将是更容易(也更正确的,见下文)如果你只是运行脚本

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

然后就可以在脚本中访问路径 $ 1 (用于参数#1,同样 $ 2 的说法#2,等)

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

file="$1"
externalprogram "$file" [other parameters]

或只是

externalprogram "$1" [otherparameters]

如果你想提取的东西路径类似 - 文件= /路径/要/文​​件,这就是通常与 getopts的<完成/ code>外壳功能。但是,这不只是引用更为复杂 $ 1 ,而且,切换像 - 文件= 的本意是可选的。我猜你的脚本的需要的要提供的文件名,所以它没有任何意义给它传递一个的选项

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

这篇关于我如何可以通过使用在Linux中终端命令文件参数,我的bash脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆