inf101cl
inf101cl

Reputation: 9

Best way to run script via a /bin/bash shell script in multiple environments?

I have a python script which I run on localhost and development in command line with argument, sth as python script.py development - on development and python script.py localhost - on localhost.

Now I want to run this script - when I running script /bin/bash sh, so I want to run this script from /bin/.bash script. I added in headers in sh script: #!/usr/bin/env python.

In what way I can achieve this?

do
    if [ $1 == "local" ]; then
      python script.py $1

    elif [ $1 == "development" ]; then
      python script.py $1

What I can do to improve this script?

Upvotes: 0

Views: 1286

Answers (2)

tripleee
tripleee

Reputation: 189387

Since $1 already contains what you want, the conditional is unnecessary.

If your script is a Bash script, you should put #!/bin/bash (or your local equivalent) in the shebang line. However, this particular script uses no Bash features, and so might usefully be coded to run POSIX sh instead.

#!/bin/sh

case $1 in
  local|development) ;;
  *) echo "Syntax: $0 local|development" >&2; exit 2;;
esac

exec python script.py "$1"

A more useful approach is to configure your local system to run the script directly with ./script.py or similar, and let the script itself take care of parsing its command-line arguments. How exactly to do that depends on your precise environment, but on most U*x-like systems, you would put #!/usr/bin/env python as the first line of script.py itself, and chmod +x the file.

Upvotes: 1

Bogdan Stoica
Bogdan Stoica

Reputation: 4539

I assume this is what you wanted...

#!/bin/bash

if [ ! "$@" ]; then
  echo "Usage: $1 (local|development) "
  exit
fi

if [ "$1" == "local" ]; then
    python script.py "$1"
    echo "$1"
elif
    [ "$1" == "development" ]; then
    python script.py "$1"
    echo "$1"
fi

Save the bash code above into a file named let's say script.sh. The make it executable: chmod +x script.sh. Then run it:

./script.sh

If no argument is specified, the script will just print an info about how to use it.

./script.sh local - executes python script.py local

./script.sh development - executes python script.py development

You can comment the lines with echo, they were left there just for debugging purposes (add a # in front of the echo lines to comment them).

Upvotes: 0

Related Questions