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
2
  • 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. Commented Jul 28, 2016 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. Commented Jul 28, 2016 at 22:41

2 Answers 2

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:
0
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.