2

How do I pass arguments when launching bash script so that specific lines are executed within the script

For example (createfile.sh):

#!/bin/bash

export CLIENT1_DIR="<path1>"
export CLIENT2_DIR="<path2>"
chef-solo -c solo.rb -j client1.json
chef-solo -c solo.rb -j client2.json

Then

$ ./createfile.sh client1

should only execute client1 specific lines, and replacing it with client2 should execute only client2 specific lines.

3

There are many solutions to this. Here's one:

#!/bin/bash

client="$1"

case "$client" in
    "client1") export CLIENT1_DIR="<path1>" ;;
    "client2") export CLIENT2_DIR="<path2>" ;;
    *)  printf 'Invalid client argument: %s\n' "$client" >&2
        exit 1 ;;
esac

chef-solo -c solo.rb -j "$client".json

The client variable gets the value of the first command line argument.

The case statement sets either CLIENT1_DIR or CLIENT2_DIR depending on this value (or exits with an error message if an invalid value was used).

Then chef-solo is invoked with the JSON file corresponding to what was given on the command line.

3

You have the lines in a function:

#!/bin/bash
clientOne(){
    ## client1 specific lines
    echo "one"
}
clientTwo(){
    ## client2 specific lines
    echo "two"
}

case "$1" in
    "client1")
        clientOne
        ;;
    "client2")
        clientTwo
        ;;
    *)
        echo "Wrong option" >&2
        ;;
esac

## Common lines
echo foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.