GarfieldKlon
GarfieldKlon

Reputation: 12140

How to add an option to a command only if a variable is equal to something?

I'd like to add the --platform option only if the variable 'platform' is equal to 'arm64', otherwise the option should not be passed in. And I don't want to duplicate the whole command and use an if-else.

platform=$(uname -m)
docker run  --platform linux/arm64 \

Upvotes: 0

Views: 135

Answers (3)

Z0OM
Z0OM

Reputation: 960

With a bash script do this:

#!/bin/bash

platform=$(uname -m)

case "$platform" in

arm64) MOD="--platform linux/arm64" ;;
*) MOD="" ;;
esac

docker run ${MOD} IMAGE [COMMAND] [ARG...]

With command line:

[[ $(uname -m) = 'arm64' ]] && VAR='--platform linux/arm64' || VAR=''

docker run ${VAR} \

Short version:

[[ $(uname -m) = 'arm64' ]] && docker run --platform linux/arm64 \ || docker run \

I have no docker on this machine check if this works too:

docker run $([[ $(uname -m) = 'arm64' ]] && echo "--platform linux/arm64") \

Upvotes: 0

tjm3772
tjm3772

Reputation: 3154

The standard bash solution for dynamic argument lists is to use an array.

#!/bin/bash
platform=$( uname -m )
docker_args=()
if [[ "$platform" = arm64 ]] ; then
  docker_args+=( "--platform" "linux/arm64" )
fi
docker run "${docker_args[@]}" \

The main benefit to this over the accepted echo solution is that arrays can safely preserve complex options such as those containing whitespace or globbing characters.

Upvotes: 0

anubhava
anubhava

Reputation: 785246

You can try this work-around:

platform=$(uname -m)
docker run $([[ $platform = arm64 ]] && echo "--platform linux/arm64") \

Upvotes: 2

Related Questions