1

I saw an expression a=($(cat)) which I am not able to understand from it's working mechanism perspective.

Functionally it takes input from the standard input and assigns it to variable a (which forms an array).

My understanding is , when shell executes the inner parenthesese it executes the cat command which brings the standard input, and when you type a few lines on the standard input and press CTRL+D it returns the lines to the outer parenthesese which then assign the lines to an array a.

My question is why this expression gives error when I remove the $ and write it as a=((cat)).

1 Answer 1

2

It is because $(..) is a command substitution syntax to run commands on. The cat in your example run in a sub-shell under this construct. Without it the command cat and ( are interpreted literally which the shell does not like

From the bash(1) - Linux man page

Command Substitution

Command substitution allows the output of a command to replace the command name. There are two forms: $(command) (or) command

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

The arithmetic operator in bash is $((..)) which is not the syntax you are using in your example

Sign up to request clarification or add additional context in comments.

5 Comments

so the output of the cat command should be treated as a command in command substitution ? I guess my syntax is an arithmetic one because there is an = operator .
@Vicky: You treat as if the cat command is run in a separate shell and its output (whatever read from stdin) is stored in to the array a
I get it now , from your command substitution explanation , Thanks Inian
I ran into another similar problem read array; arr=(echo $array) executes echo and assigns the output to arr but a=(cat file.txt) assigns "cat file.txt" to a, it is not assigning contents of file.txt to a I guess cat in later case is being teated as a simple string in absence of command substitution operator $( ..) but how is echo able to execute without command substitution.
@Vicky: Do ask it as a question under bash. As such the context of your old question is complete

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.