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)
4
  • I know this is a duplicate of a previously asked and answered question, but my search skills are failing me and I can't find the previous question.
    – John
    May 29, 2015 at 16:06
  • 1
    You mean you want to save output of /bin/ps wwwaux into variable A?
    – cuonglm
    May 29, 2015 at 16:09
  • @cuonglm NO. I want to put command-string as it is, with spaces, to A variable. May 29, 2015 at 16:15
  • "somewhy" That's a new one :) May 29, 2015 at 18:11

2 Answers 2

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
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.

Not the answer you're looking for? Browse other questions tagged .