Pablo
Pablo

Reputation: 10602

Bash: Add inline if to modify script

I'm writing a bash script where I need to do 2 different actions depending on the arguments.

For example calling my script without params (./script) it should do this:

docker-compose run ...

how ever if I send a param to my script (./script -d) it should do this:

docker-compose -f file run...

So the -f file is the only part added based on the argument. I dont want to repeat the whole code in each if statement, is there a better way?

Upvotes: 2

Views: 179

Answers (3)

ghoti
ghoti

Reputation: 46856

There are many ways to parse arguments. A test (or [[) is the simplest approach, though if there's the possibility of multiple conditions, a case statement might be preferable:

#!/usr/bin/env bash

case "$1" in;
  -d) args=( -f "file" ) ;;
  "") args=() ;;
  *) echo "Usage error." >/dev/null; exit 1 ;;
esac

docker-compose "${args[@]}" run

For larger scale options handling, getopts is probably the way to go:

#/usr/bin/env bash

args=()
while getopts hdf: opt; do
  case "$opt" in
    h) printf "Usage: ${0##*/} [-d]"; exit 0 ;;
    d) args=( -f "file" ) ;;       # use a static file
    f) args=( -f "$OPTARG" ) ;;    # use a user-specified file
  esac
done
shift $((OPTIND - 1))

docker-compose "${args[@]}" run

For usage information, search the "SHELL BUILTIN COMMANDS" section for getopts.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361675

One option is to use an array. If -d is present then add -f "$file" to the array.

args=()
[[ $1 == -d ]] && args+=(-f "$file")
docker-compose "${args[@]}" run...

Another is to use :+ to substitute an alternate value only when a variable is set. If $option is set to -d then substitute -f "$file"; if it's empty then leave it empty.

option=
[[ $1 == -d ]] && option=-d
docker-compose ${option:+-f "$file"} run...

Both of these options will handle file names that contain whitespace correctly.

Upvotes: 3

michael
michael

Reputation: 9779

Many different ways to handle args (including getopts), but most simply,

#!/bin/bash

# by default, set to none; otherwise, set to some value
[ "$1" = "-d" ] && args="-f file" || args=

docker-compose $args run ...

Upvotes: 0

Related Questions