2

I cannot set a variable with a whole command-string as following:

A="/bin/ps wwwaux"

for a in $A
do
  echo "$a"
done

It assigns array instead of solid string someway.

My environment:

GNU/Linux, GNU bash, version 3.2.51(1)-release (x86_64-suse-linux-gnu)
Rui F Ribeiro
  • 55,929
  • 26
  • 146
  • 227
user1065145
  • 407
  • 1
  • 6
  • 14

2 Answers2

8

The for loop expects a list:

for a in $A; do
  echo "$a"
done

Expands to:

for a in /bin/ps wwwaux; do
  echo "$a"
done

Which prints both after each other. The loop runs twice, because there are TWO arguments. The output will be:

/bin/ps
wwwaux

Use quotes instead:

for a in "$A"; do
  echo "$a"
done

This will expands to:

for a in "/bin/ps wwwaux"; do
  echo "$a"
done

Which will loop exactly once, because it's ONE argument. That's the output:

/bin/ps wwwaux
chaos
  • 47,463
  • 11
  • 118
  • 144
5
for f in "$A"
do
  echo $f
done

Your assignment is already doing what you want - it's the "for" loop that's breaking it up in a way you don't want.

John
  • 16,759
  • 1
  • 34
  • 43