37

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lanrest
  • 379
  • 1
  • 3
  • 6
  • 4
    You can use `getopts` for this purpose. There are many tutorials, something like http://aplawrence.com/Unix/getopts.html can be useful for a start. – fedorqui May 01 '13 at 14:13
  • Thanks, I saw this on the questions I linked. I was wondering if there is some standard way to have command arguments overwrite variables. For example when defining functions in python it is possible to set a default value. I can see that with an if check I could replace the default with the command line argument, but was unsure if there was a standard way of doing this? – Lanrest May 01 '13 at 14:48

2 Answers2

87

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
codeape
  • 97,830
  • 24
  • 159
  • 188
8

Instead of using command line arguments to overwrite default values, you can also set the variables outside of the script. For example, the following script can be invoked with foo=54 /tmp/foobar or bar=/var/tmp /tmp/foobar:

#! /bin/bash
: ${foo:=42}
: ${bar:=/tmp}
echo "foo=$foo bar=$bar"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
nosid
  • 48,932
  • 13
  • 112
  • 139
  • 1
    I thought about this, however the script I am editing is for people with even less familiarity than myself. I want to make it as simple as possible, and I think command line arguments are somthing they are more familiar with. – Lanrest May 01 '13 at 15:32