Berk U.
Berk U.

Reputation: 7198

Passing variables to a bash script with default values

I currently have a bash script in which I have hard coded certain variables, and I was hoping to be able to set these variables by passing arguments.

A simple example: consider the script example.sh where I have hard coded values for the variables data_names and run_this

#!/bin/bash

data_names=("apple_picking" "iris")
run_this="TRUE"    

#remainder of script runs things using these hard coded variables

I am wondering if it is possible to edit this script so that:

  1. I can set the values of data_names and run_this by passing arguments when I run bash example.sh

  2. If no arguments are passed for either data_names and run_this to the script, then the variables should take on default (hard coded) values.

Upvotes: 1

Views: 430

Answers (3)

Wrikken
Wrikken

Reputation: 70540

Another option is like this:

  run_this=${1:-TRUE}
  IFS=',' read -a data_names <<< "${2:-apple_picking,iris}"

Assuming your script is called like:

 ./script.sh first_argument array,values,in,second,argument

Upvotes: 0

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 185790

If you want something robust, clear & elegant, you should take a look to getopts to set run_this

Tutorial: http://wiki.bash-hackers.org/howto/getopts_tutorial Examples: http://mywiki.wooledge.org/BashFAQ/035

I think of something like :

./script --run-this=true "apple_picking" "iris"

Upvotes: 2

anubhava
anubhava

Reputation: 786091

You can use:

#!/bin/bash

# create a BASH array using passed arguments
data_names=("$@")

# if array is empty assign hard coded values
[[ ${#data_names[@]} -eq 0 ]] && data_names=("apple_picking" "iris")

# print argument array or do something else
printf "%s\n" "${data_names[@]}";

Upvotes: 0

Related Questions