Hi everyone, I have problems with this script.
This script should check for a folder for each server in the list of the list.txt file.
The script only checks the first host, and then exits, why?
#!/bin/bash
file='/etc/list.txt'
while read line; do
echo $line
if ssh root@$line "stat /var > /dev/null 2>&1"; then
echo "File exists"
else
echo "File does not exist"
fi
done < $file
thank you very much for helping
n
I haven't used ssh for a long time, but if memory serves - I think you need to use the -n option.
Without it, ssh treats everything else in your script as input from stdin. Which is why in your script, the reason that only the first server is responding is because it's the only ssh session being fired off.
The rest of the script is being consumed as input to the initial ssh command..... I think!
Using the -n option should prevent ssh from hogging stdin and fix your problem.
Consider this slightly modified version of your script:
Code:
#!/usr/bin/env bash
file="/etc/list.txt"
while read host; do
echo "$host"
if ssh -n "root@$host" "stat /var > /dev/null 2>&1"; then
echo "File exists"
else
echo "File does not exist"
fi
done < "$file"
NOTES:
Above is your original script, but with some very pedantic, minor alterations.
- I renamed the variable $line to $host, to make it a bit clearer what each line in the file represented.
- I used double quotes every time we dereferenced a variable. I have a shellcheck plugin in vim which complains every time there are unquoted variables in a shell-script, so I automatically double quote them now. It's a habit!
- I changed the shebang line - because on some systems bash is in /bin/ and in others it's in /usr/bin/. This is just another habit I've picked up! There's nothing worse than trying to run one of your scripts on another machine and have it fail because the path to the interpreter was incorrect. So I always use "#!/usr/bin/env bash" in my scripts (Or "#!/usr/bin/env sh" for more generic, non-bash specific scripts). Let each system decide which bash (or shell) to run! Basically, I'm too lazy to have to edit the script each time I run it on a different machine! XD
- most importantly, I added the -n option to the ssh command.
Also, I haven't tested the script. I don't currently have ssh access to any servers, so I have no way to test it. So at the risk of ending up with egg on my face - I'll leave It to you to try!
And by all means, ignore most of my alterations. The the most important thing to try in your script is the ssh command's -n option. That should hopefully prevent the problem you were having!