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?

2

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.