I have a script which has several input files, generally these are defaults stored in a standard place and called by the script.
However, sometimes it is necessary to run it with changed inputs.
In the script I currently have, say, three variables, $A $B, and $C. Now I want to run it with a non default $B, and tomorrow I may want to run it with a non default $A and $B.
I have had a look around at how to parse command line arguments:
How do I parse command line arguments in Bash?
How do I deal with having some set by command line arguments some of the time?
I don't have enough reputation points to answer my own question. However, I have a solution:
Override a variable in a Bash script from the command line
#!/bin/bash a=input1 b=input2 c=input3 while getopts "a:b:c:" flag do case $flag in a) a=$OPTARG;; b) b=$OPTARG;; c) c=$OPTARG;; esac done
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
$# is typically used in bash scripts to ensure a parameter is passed. Generally, you check for a parameter at the beginning of your script. To summarize $# reports the number of parameters passed to a script. In your case, you passed no parameters and the reported result is 0 .
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
You can do it the following way. See Shell Parameter Expansion on the Bash man page.
#! /bin/bash value=${1:-the default value} echo value=$value
On the command line:
$ ./myscript.sh value=the default value $ ./myscript.sh foobar value=foobar
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