Know Nothing
Know Nothing

Reputation: 1251

How does this command substitution with "cat" work?

I've found a shell script that has a line like this:

#!/bin/bash

myfile=$1

variable=`cat`
# other commands go here

I don't understand, will that variable contain? When I tried the same thing in the command prompt, it just waited for stdin to close.

Upvotes: 0

Views: 639

Answers (3)

Aaron
Aaron

Reputation: 24802

The script probably relies on being executed with a non-tty stdin, in which case the variable will contain its whole content without need for any user interaction :

#!/bin/bash
variable=`cat`
echo $variable
$ echo foo | script.sh
foo
$ echo foo > some_file
$ script.sh < some_file
foo

Upvotes: 1

Benjamin W.
Benjamin W.

Reputation: 52112

This will expect keyboard input (or read from standard input if invoked in a pipe), and after closing standard input with CtrlD, variable will contain what was typed.

The much more common way of achieving this is using the read builtin, though:

$ read variable
foo
$ declare -p variable
declare -- variable="foo"

Upvotes: 3

fratardi
fratardi

Reputation: 73

Cat takes two files and display both of them if you do cat file1.txt file2.txt on your terminal any that your files exists and contain data it will output the content of file1.txt then the content of file2.txt if you want more infos look at man pages over the internets for more precisions [http://man7.org/linux/man-pages/man1/cat.1.html][1]

Upvotes: -1

Related Questions