Operating System - Linux
1748181 Members
4076 Online
108759 Solutions
New Discussion юеВ

Re: Modify ksh script to accept input from file

 
Stuart Abramson
Trusted Contributor

Modify ksh script to accept input from file

I wrote a script (let's call it the 2nd script) to process a file, which was a required argument:

...script [file]

Inside the sciprt I check some stuff and go:

...INFILE=$1

and thenn operate on $INFILE.

Now I find I want to pipe the output of another script (my 1st script) into my 2nd script.

..first_script.ksh | second_script.ksh

so that my 2nd script has no argument now.

How do I modify the 2nd script to take standard input if no file is specified; or read a file if a file is specified?

I tried:

...INFILE=&0

but that didn't do it...

5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: Modify ksh script to accept input from file

Hi Stuart:

Do something like this:

[ -z "${1}" ] && exec < /dev/tty || exec < ${1}

...instead of :

INFILE=$1

Regards!

...JRF...
Sandman!
Honored Contributor

Re: Modify ksh script to accept input from file

Stuart,

Pipe stdin with xargs w/o changing code in the 2nd script to get the result...

# first_script.ksh | xargs second_script.ksh

...this way you don't need to change the definition of INFILE=$1.

cheers!
john korterman
Honored Contributor

Re: Modify ksh script to accept input from file

Hi,

try this in 2nd script:


#!/usr/bin/sh

if [ -t 0 ]
then
echo I am not piped to, read parameter
INFILE=$1
else
while read line
do
echo processing std in from $line
done
fi
~


regards,
John K
it would be nice if you always got a second chance
Howard Marshall
Regular Advisor

Re: Modify ksh script to accept input from file

I fear the real, correct answer to your question is going to reside in how you wrote the 2nd script. If you make several references to the input file during your script you may have problems.

You may only have to make very small changes to the script, you may have to do a major renovation, epically if you want to keep both capabilities.

Another option, though somewhat less efficient, is to give your 2nd script a flag that takes piped input and just writes it to a temp file and then uses that tmp file name as the parameter for the input file. I know that├в s kind of dirty and you have to remember to clean up the file at the end too but it requires less script renovation and the script works basically the same way for either piped or file name data.

Howard
Stuart Abramson
Trusted Contributor

Re: Modify ksh script to accept input from file

JRF led me to the correct answer:

He wrote:

[ -z "${1}" ] && exec
The correct answer was:

[ -z "${1}" ] && exec<&0 || exec<${1}

i.e. - take input from "stdin" if $1 zero, or from $1 if $1 is non-zero.

Points not working - I'll do them tomorrow.