-4

So doing

$(cat /etc/passwd)

results in "No such File or Directory"

and

"$(whereis cat)"

results in "command not found"

Why is command substitution not working in the expected manner?

4
  • It would be helpful if you could reproduce the full error message in your question, ideally copy-and-paste the command and the result from your console Commented Dec 6, 2024 at 16:00
  • 4
    What are you trying to achieve with command substitution? Commented Dec 6, 2024 at 16:04
  • 3
    Please edit your question and explain what you want to achieve with your commands. Commented Dec 6, 2024 at 16:12
  • 1
    Quite likely a duplicate of unix.stackexchange.com/questions/167701 and similar questions. Commented Dec 6, 2024 at 16:13

1 Answer 1

5

TL;DR: You may be using command substitution the wrong way.

While you do not provide the full error message, it is very likely that the command substitution works exactly the way it is intended.

Command substitution means that the output of a command is put in the place where the command substitution is specified. That means if you have a script with a line

$(cat /etc/passwd)

the script will try to execute the content of the file /etc/passwd, as printed by cat, which consists of :-separated fields like

root:x:0:0:root:/root:/bin/ash

which of course is not a valid command.

Similarly, if you have a line

$(whereis cat)

in your script, it will try to execute the "command"

cat: /bin/cat /usr/share/man/man1/cat.1.gz

(or similar, depending on your distribution) which will fail because there is no command cat: on your system. This is aggravated by your use of " ... "-quoting - usually the right thing to do - which makes the shell treat the entire line (including spaces) as one command name that it tries to execute.

2
  • IMHO adding an example showing the use of command substitution for variable assignment would help here. Likely what the OP wanted is something like users="$(cat /etc/passwd)". Shell substitutes the contents of $() with its output, both in variable assignment and in OP's example; the difference is that one is a command invocation, while the other is specifically a variable assignment. Commented Dec 6, 2024 at 17:40
  • By the way, in practice, double-quotes in the above assignment are not necessary, though the standard is vague: "Any such bytes that occur elsewhere shall be included in the replacement; however, they might be treated as field delimiters and eliminated during field splitting, depending on the value of IFS and quoting that is in effect." (emphasis mine) Commented Dec 6, 2024 at 17:40

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.