Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash command line arguments, replacing defaults for variables

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 
like image 679
Lanrest Avatar asked May 01 '13 14:05

Lanrest


People also ask

What does $@ mean in bash?

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.

What does $# do in bash?

$# 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 .

What is $_ bash?

$_ (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.


1 Answers

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 
like image 147
codeape Avatar answered Sep 24 '22 01:09

codeape