0

I'm Trying to create a simple shell script to loop through a file line by line and execute a command with each line as a variable.

Here is my Text File:

FakeAccount
FakeUser 

Here Is My Shell Script:

#!/bin/bash

while IFS= read -r line; do
    "echo -e 'testpassword\ntestpassword' | passwd $line"
done < "User.txt"

The Output i get back seems to be what i want, the output says:

"line 4: echo -e 'testpasswd\ntestpasswd' | passwd FakeAccount: command not found"

"line 4: echo -e 'testpasswd\ntestpasswd' | passwd FakeUser: command not found"

But if i copy this exact string: echo -e 'testpasswd\ntestpasswd' | passwd FakeUser

the command works just fine so why is the shell script not executing the command and its saying command not found?

2
  • 3
    Why do you double quote the body of the loop? See also unix.stackexchange.com/questions/345459/…
    – Kusalananda
    Oct 23, 2018 at 19:38
  • Beware anyone that has an account on this machine, can read the full command line and arguments of any command (so the password). (Unless you employ namespaces) Oct 23, 2018 at 19:59

2 Answers 2

1

By enclosing the command and their arguments into double quotes, you're presenting the whole string as a single command which is, as the shell tells you, not found.

The shell needs to perform word splitting in order to find command lists, assignments, commands, and their parameters (see the opening sections of man bash to learn more).

Don't use double quotes on the whole pipeline, just quote the variable:

echo -e 'testpassword\ntestpassword' | passwd "$line"
3
  • Does your passwd read from standard input? ;-)
    – Kusalananda
    Oct 23, 2018 at 19:52
  • Yes it is looking for and can not find a command named echo -e 'testpasswd\ntestpasswd' | passwd FakeAccount Oct 23, 2018 at 19:58
  • @Kusalananda: I haven't tried it, but the OP states But if i copy this exact string... the command works just fine
    – choroba
    Oct 23, 2018 at 19:58
0

You could do it even simpler as follows using chpasswd:

while read -r user; do printf "$user:%s" "some_secret_pass" | chpasswd ; done < User.txt

Or if you want to use passwd then you'd probably need to pass the --stdin flag. As far as I can see, this is supported in recent Fedora and Centos releases

Using passwd:

while read -r user; do printf %s\\n "some_secret_pass" | passwd --stdin "$user" ; done < User.txt

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .