Here are some issues; not sure I found all of them.
- The shebang line lacks the
#
which is significant and crucial.
- There is no need to read the server names into a variable, and in addition to wasting memory, you are exposing yourself to a number of potential problems; see https://mywiki.wooledge.org/DontReadLinesWithFor
- Unless you specifically require the shell to do whitespace tokenization and wildcard expansion on a value, put it in double quotes (or even single quotes, but this inhibits variable expansion, which you still want).
- If you are logging in as
root
, no need to explicitly sudo
.
ssh
runs a shell for you; no need to explicitly sh -c
your commands.
- On the other hand, you want to avoid running a root shell if you can. A common way to get to append to a file without having to spawn a shell just to be able to redirect is to use
tee -a
(just drop the -a
to overwrite instead of append). Also printing the file to standard output is an undesired effect (some would say the main effect rather than side effect of tee
but let's just not go there) so you often redirect to /dev/null
to avoid having the text also spill onto your screen.
- You probably want to avoid a useless use of
cat
if only just to avoid having somebody point out to you that it's useless.
#!/bin/bash
while read -r server; do
do
ssh you@"$server" sudo tee -a /etc/ntp.conf <ntp.txt >/dev/null
done <servers.txt
I changed the code to log in as you
but it's of course something you will need to adapt to suit your environment. (If you log in as yourself, you usually just ssh server
without explicitly specifying a user name.)
As per your comment, I also added a full path to the destination file /etc/ntp.conf
A more disciplined approach to server configuration is to use something like CFengine2 to manage configurations.