0

I have a small problem here.

I've written a script, which works fine. But there is a small problem.

The script takes 1 or 2 arguments. The 2nd arguments is a .txt file.

If you write something like my_script arg1 test.txt, the script will work. But when you write my_script arg1 < test.txt it doesn't.

Here is a demo of my code:

#!/bin/bash

if [[ $# = 0 || $# > 2 ]]
then
    exit 1
elif [[ $# = 1 || $# = 2 ]]
then
    #do stuff

    if [ ! -z $2 ]
    then
        IN=$2
    else
        exit 3
    fi
fi

cat $IN

How can I make it work with my_script arg1 < test.txt?

vixero
  • 514
  • 1
  • 9
  • 21

2 Answers2

2

If you just want to change how my_script is called, then just let cat read from myscript's standard input by giving it no argument:

#!/bin/bash

if [[ $# != 0 ]]
then
    exit 1
fi
cat

If you want your script to work with either myscript arg1 < test.txt or myscript arg1 test.txt, just check the number of arguments and act accordingly.

#!/bin/bash

case $# in
   0) exit 1 ;;
   1) cat ;;
   2) cat $2 ;;
esac
chepner
  • 497,756
  • 71
  • 530
  • 681
0

If you look at how the guys at bashnative implemented their cat you should be able to use 'read' to get the piped content..

eg. do something like this:

   while read line; do
      echo -n "$line"
   done <"${1}"

HTH,

bovako

Thijs Dalhuijsen
  • 768
  • 6
  • 14