Getting the following error: -bash: 1: command not found when trying to execute for loop
Solution 1
What the shell does when it sees echo $($x >> c.txt)
is to first handle the command substitution $($x >> c.txt)
. This would be replace by the output of the command $x >> c.txt
. The $x
is 1
in the first iteration of the loop, but there is no such command, hence the errors (there would be one error for each iteration of the loop if you have no commands corresponding to the integers in the range 1 to 10; the output in the question is probably truncated).
You may have wanted to do something like
for x in $(seq 10); do
echo "$x" >>c.txt
done
(without a command substitution), or just
seq 10 >>c.txt
which would have an equivalent effect.
Solution 2
On first execution of the loop, x
will be 1
, so you execute echo $(1 >> c.txt)
and the shell tries to execute 1
, which is not found.
If you add what you are actually trying to do, we can point out what to change.
Related videos on Youtube
boomselector
Updated on September 18, 2022Comments
-
boomselector over 1 year
When i try to execute the following command:
for x in $(seq 10); do echo $($x >> c.txt); done
I get the following error:
-bash: 1: command not found
-
Kusalananda over 4 yearsThere is no indication that the given command is part of a script. If it was, the error message would have been prefixed by the name of the script, not by
-bash
(which indicates that the error is produced by the user's interactive login shell). -
Galdor over 4 years@Kusalananda There's also no indication that the OP pasted the full output of the script or one-liner error, if that's the case i'll delete my answer. Thanks for the insight.
-
Kusalananda over 4 yearsThe full output would include similar error messages for each integer between 1 and 10, so you are correct that the question contains a truncated output.
-
boomselector over 4 yearsthanks, this helped!
-
Kusalananda over 4 years@boomselector Rather than adding a separate "Thank you", upvote the answer(s) that helped you, and consider "accepting" the answer that was the most helpful in resolving your issue. These are the best ways of showing gratitude on this site. Accepting an answer not only marks the question as resolved, but also signals to future readers that the accepted answer actually solved the issue. More information about this is available here: unix.stackexchange.com/help/someone-answers