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

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

问题描述

所以我的问题是如何在 Linux 中使用终端命令将文件参数传递给我的 bash 脚本?目前,我正在尝试在 bash 中创建一个程序,该程序可以从终端获取文件参数并将其用作我程序中的变量.例如我跑myprogram --file=/path/to/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]

如果您想从 --file=/path/to/file 之类的东西中提取路径,通常使用 getopts shell 函数来完成.但这比仅仅引用 $1 更复杂,此外,像 --file= 这样的开关是可选的.我猜你的脚本要求提供一个文件名,所以在选项中传递它是没有意义的.

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天全站免登陆