41

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
2
  • 4
    You can use getopts for this purpose. There are many tutorials, something like aplawrence.com/Unix/getopts.html can be useful for a start. Commented May 1, 2013 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? Commented May 1, 2013 at 14:48

2 Answers 2

94

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
Sign up to request clarification or add additional context in comments.

Comments

10

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"

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.