1

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.

1
  • 1
    Yes, it is possible. What have you tried so far and what happened? Commented Dec 10, 2014 at 22:14

3 Answers 3

2

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

2 Comments

Thank you for this! This is the best option by far since it doesn't require input arguments to be specified in a given order / can handle multiple input arguments.
Sure, that's the goal of the proposed solution HTH
0

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[@]}";

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.