Home > Back-end >  Shell script: know when there is redirected input
Shell script: know when there is redirected input

Time:11-21

I am trying to figure out a way for a shell script to know when some input has been redirected in order to run a python script with different command line args. My shell script is called P2 and the possible invocations need to be (unfortunately no flexibility on this):

1. P2
2. P2 < someFile
3. P2 someFile

and ideally, the shell script pseudocode would work like this:

if argCount == 2:
  run (python P2.py someFile)
else:
  if inputWasRedirected: **********_issue is here_**********
    run (python P2.py < someFile)
  else:
    run (python P2.py)

Any and all help would be appreciated.

CodePudding user response:

#!/bin/sh

if test -n "$1"; then
    echo "Your input is : $1";
elif test ! -t 0; then
    echo "Read from stdin"
    input=$(cat)
    echo your input is :  $input;
else
    echo "No data provided..."
fi

As you can see Check if no command line arguments and STDIN is empty, the major tricks are as follow:

  • Detecting that you have an argument is done through the test -n $1 which is checking if a first argument exists.

  • Then, checking if stdin is not open on the terminal (because it is piped to a file) is done with test ! -t 0 (check if the file descriptor zero (aka stdin) is not open).

  • And, finally, everything else fall in the last case (No data provided...).

CodePudding user response:

If the python script is written properly, you don't need to handle anything. Just pass the script arguments ("$@") to python:

#!/bin/sh
python P2.py "$@"

"$@" expands to all arguments given to the shell script (including expanding to nothing if no arguments given).

Python also inherits any stdin redirection of the shell.

It's up to the python script to prefer file arguments over stdin (conventional behaviour).

Eg. test, using cat instead of python:

#!/bin/sh
cat "$@"
  • For ./test a b < c, files a and b are printed.
  • For ./test < c file c is printed.
  • For ./test, cat reads input from the terminal.
  • Related