Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read stdin when no arguments are passed?

Tags:

bash

stdin

Script doesn't work when I want to use standard input when there are no arguments (files) passed. Is there any way how to use stdin instead of a file in this code?

I tried this:

if [ ! -n $1 ] # check if argument exists
   then
   $1=$(</dev/stdin)  # if not use stdin as an argument
   fi

var="$1"
while read line
   do
   ...                # find the longest line
   done <"$var"
like image 686
aron23 Avatar asked Oct 27 '13 14:10

aron23


People also ask

Are command line arguments stdin?

Yes, command line arguments have no relation with stdin and stdin in that case is just pointing to your input device but not being used. stdin is itself is a file which by default points to your input device and takes input from there.

What is stdin in shell script?

In Linux, stdin is the standard input stream. This accepts text as its input. Text output from the command to the shell is delivered via the stdout (standard out) stream. Error messages from the command are sent through the stderr (standard error) stream.


2 Answers

For a general case of wanting to read a value from stdin when a parameter is missing, this will work.

$ echo param | script.sh
$ script.sh param

script.sh

#!/bin/bash

set -- "${1:-$(</dev/stdin)}" "${@:2}"

echo $1
like image 176
Ryan Avatar answered Sep 22 '22 12:09

Ryan


Just substitute bash's specially interpreted /dev/stdin as the filename:

VAR=$1
while read blah; do
  ...
done < "${VAR:-/dev/stdin}"

(Note that bash will actually use that special file /dev/stdin if built for an OS that offers it, but since bash 2.04 will work around that file's absence on systems that do not support it.)

like image 41
pilcrow Avatar answered Sep 20 '22 12:09

pilcrow