3

I am creating a script and when I try to capture a command return, I have an error of command not found, if I use this command on the terminal:

gcloud -q compute snapshots list --format='csv(NAME)'

It works fine.

The script is:

#!/bin/sh
CSV_SNAPSHOTS= $(gcloud -q compute snapshots list --format='csv(NAME)')
IFS=$'\n'

for i in $CSV_SNAPSHOTS
do
    echo "$i"
done
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Renan Otero
  • 41
  • 1
  • 3
  • I don't think you want glob expansion on the words resulting of the splitting of $CSV_SNAPSHOTS, so you should probably issue a set -o noglob before that for loop. – Stéphane Chazelas Jul 28 '16 at 14:42
  • Depending on what's at /bin/sh (If it's an actual Bourne shell, for instance) the modern $(command) metaphor may not even be supported. – Monty Harder Jul 28 '16 at 22:41

2 Answers2

9

There must not be any whitespace after = (and also before =) in variable declaration.

So this should do:

CSV_SNAPSHOTS=$(gcloud -q compute snapshots list --format='csv(NAME)')

Also note that, you should (almost always) quote variable and command substitution, although you would get away in this case as you are saving the command substitution to a variable.


Example:

$ foo="$(echo spam)"
$ echo "$foo"
spam

$ bar= "$(echo egg)"
No command 'egg' found, did you mean:
heemayl
  • 56,300
3

The error is the space after the =, but you could also bypass storing the output in a variable and instead read it directly into your loop:

IFS=$'\n'

gcloud -q compute snapshots list --format='csv(NAME)' |
while read -r i; do
    printf "%s\n" "$i"
done
Kusalananda
  • 333,661