This question already has an answer here:
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.
My Program
#!/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
Then you can access the path within the script as
$1
(for argument #1, similarly$2
is argument #2, etc.)Or just
If you want to extract the path from something like
--file=/path/to/file
, that's usually done with thegetopts
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.you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:
see also:
man getopt
Assuming you do as David Zaslavsky suggests, so that the first argument simply is the program to run (no option-parsing required), you're dealing with the question of how to pass arguments 2 and on to your external program. Here's a convenient way:
The
shift
will remove the first argument, renaming the rest ($2
becomes$1, and so on).
$@` refers to the arguments, as an array of words (it must be quoted!).If you must have your
--file
syntax (for example, if there's a default program to run, so the user doesn't necessarily have to supply one), just replaceext_program="$1"
with whatever parsing of$1
you need to do, perhaps using getopt or getopts.If you want to roll your own, for just the one specific case, you could do something like this:
Bash supports a concept called "Positional Parameters". These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.
Positional parameters are referred to by the names
$0
,$1
,$2
... and so on.$0
is the name of the script itself,$1
is the first argument to the script,$2
the second, etc.$*
represents all of the positional parameters, except for$0
(i.e. starting with$1
).An example: