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?

red_kb
  • 85
  • 7
  • to access the parameters on the command line in python, use import sys. sys.argv is a list containing the parameters. – ShpielMeister Aug 23 '18 at 03: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. – red_kb Aug 23 '18 at 03:34

1 Answers1

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
John Gordon
  • 29,573
  • 7
  • 33
  • 58
  • you don't really need to check $f1 – Jonah Aug 23 '18 at 03:47
  • @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. – John Gordon Aug 23 '18 at 03:52
  • I'm pretty sure that's not how bash handles it... Try it out with a script that prints sys.argv. – Jonah Aug 23 '18 at 04:08