stack
stack

Reputation: 841

How to define a value in bash shell for?

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?

Upvotes: 1

Views: 58

Answers (2)

KamilCuk
KamilCuk

Reputation: 140990

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

Upvotes: 2

Amadan
Amadan

Reputation: 198314

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.

Upvotes: 4

Related Questions