Home > Enterprise >  How to takes bash script input from both pipe
How to takes bash script input from both pipe

Time:02-10

I want to take my script input from these 3 conditions. How can i do that in bash :)

Condition : 1

cat text.txt | ./myscript.sh

Hello
Hello1
Hello2

Condition :2

./myscript.sh text.txt

Hello
Hello1
Hello2

Condition :3

./myscript.sh single-word

single-word

CodePudding user response:

Use "${@:--}" within the script as the input source - that'll use arguments if present or stdin otherwise:

$ cat tst.sh
#!/usr/bin/env bash

awk '{ print FILENAME, $0 }' "${@:--}"

$ cat text.txt | ./tst.sh
- Hello
- Hello1
- Hello2

$ ./tst.sh text.txt
text.txt Hello
text.txt Hello1
text.txt Hello2

CodePudding user response:

If you only have 1 parameter:

#!/bin/bash
#
printf "$(cat $1)\n"
  • Related