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?
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
Shift operator in bash (syntactically shift n, where n is the number of positions to move) shifts the position of the command line arguments. The default value for n is one if not specified. The shift operator causes the indexing of the input to start from the shifted position.
To invoke a function, simply use the function name as a command. To pass parameters to the function, add space separated arguments like other commands. The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.
It'll be easier (and more "proper", see below) if you just run your script as
myprogram /path/to/file
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]
Or just
externalprogram "$1" [otherparameters]
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.
you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:
#!/bin/sh OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@") if [ $? -ne 0 ]; then echo "getopt error" exit 1 fi eval set -- $OPTIONS while true; do case "$1" in -h|--help) HELP=1 ;; -f|--file) FILE="$2" ; shift ;; -g|--foo) FOO=1 ;; -b|--bar) BAR=1 ;; --) shift ; break ;; *) echo "unknown option: $1" ; exit 1 ;; esac shift done if [ $# -ne 0 ]; then echo "unknown option(s): $@" exit 1 fi echo "help: $HELP" echo "file: $FILE" echo "foo: $FOO" echo "bar: $BAR"
see also:
man getopt
links dead. here from internet archive:
https://web.archive.org/web/20100325015445/http://software.frodo.looijaard.name/getopt/docs/getopt-parse.bash
https://web.archive.org/web/20130827004301/http://www.missiondata.com/blog/system-administration/17/17/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With