1

I have a problem while using sh linshi.sh.

The content of linshi.sh is:

for i in `cat host-user.txt`
  do
    host = awk '{print $1}' $i
    user = awk '{print $2}' $i
    echo $host
    echo $user
    ssh $hosts pkill -u $user
 done

The content of host-user.txt is:

node1 john
node2 snow
node3 aya
node4 stack

But unlucky it doesn't work, it shows nothing. How to correctly define my variables?

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49
stack
  • 821
  • 1
  • 15
  • 28
  • 2
    Run this code through [ShellCheck](https://www.shellcheck.net/) to correct the errors. Also see [this answer](https://stackoverflow.com/questions/28290174) which explains why this `ssh` command will fail – arco444 Aug 24 '18 at 09:48

2 Answers2

4

There are several problems here. The direct answer to your question is bash doesn't allow spaces around the assignment operator.

# BAD
foo = bar

# GOOD
foo=bar

But I need to continue: the for line doesn't do what you want. The backticks will expand the output and split by whitespace, so you end up with for i in node1 john node2 snow node3 aya node4 stack, which gives you eight iterations with $i being one word, not four iterations with $i being one line. If you want to iterate over lines, use read.

Also, there can't be any spaces inside the value of an assignment, unless the value is quoted. If you write host=awk '{print $1}' $i, it will make host have the value awk, then launch a subshell and try to run the program {print $1} with the parameter that is the value of i - not what you meant. But you actually probably meant that you want to run awk, and here you'd use the backtick quotes, or even better $(...) because it allows nesting and is clearer to read.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • I have tested while read as Kamil Cuk said. But it would be stopped while running ssh command – stack Aug 27 '18 at 09:33
  • I did not think I need to repeat the warning from arco444. I answered your question - how to correctly define your variables; your `ssh` problem is unrelated. – Amadan Aug 27 '18 at 09:34
2

Use while read to read from file:

while read -r host user; do
    echo "$host"
    echo "$user"
    ssh "$host" pkill -u "$user" </dev/null
done <host-user.txt

for i in $(cat ...) - never do that, see here
host = ... - theres is no space before and after = when assigning
= awk ... - get the output of the command using "$(..)` expression

KamilCuk
  • 120,984
  • 8
  • 59
  • 111