0

I am writing a Python script that is started by a .sh file and accepts 2-3 parameters. I have written what I want in Java, but I'm not sure how to put in bash.

Scanner i = new Scanner(System.in);
String f, f1, f2;

System.out.print("Enter type: ");
f = i.next();

if (f.equals("a")){
  System.out.print("Enter var1");
  f1 = i.next();
  // run "python script.py a [f1]"
}

else if (f.equals("b")){
  System.out.print("Enter var1");
  f1 = i.next();
  System.out.print("Enter var2");
  f2 = i.next();
  // run "python script.py b [f1] [f2]"
}

This is what I have so far:

a="e"
b="test.txt"
c=""
python main.py "$a" "$b" "$c"

I've looked at How to concatenate string variables in Bash, but I'm not sure how to put it in a conditional statement.

How do I put the read-ins in conditional statements in bash?

2
  • to access the parameters on the command line in python, use import sys. sys.argv is a list containing the parameters. Commented Aug 23, 2018 at 3:30
  • I know, but how do you get the input in bash? What you are saying happens after the input is entered and the script is executed. Commented Aug 23, 2018 at 3:34

1 Answer 1

1

Here's a starter Bash script:

echo "Enter type"
read f

if [ "$f" = "a" ]; then
    echo "Enter var1"
    read f1
    if [ -z "$f1" ]; then
        # -z means "variable is empty", i.e. user only pressed Enter
        python script.py "$f"
    else
        python script.py "$f" "$f1"
    fi
fi
Sign up to request clarification or add additional context in comments.

3 Comments

you don't really need to check $f1
@Jonah If you don't check $f1, and the user didn't enter a value, the python script will see an empty string as the third arg, which you probably don't want.
I'm pretty sure that's not how bash handles it... Try it out with a script that prints sys.argv.

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.