Gábor Varga
Gábor Varga

Reputation: 840

Command result to a variabe in for loop shell script

How to: a command result to a variable?

for file in find "$1" do
    var = $file | cut -d/ -f6-
    echo $var
    ...
done

Upvotes: 0

Views: 438

Answers (2)

sorpigal
sorpigal

Reputation: 26086

A few pointers:

In shell scripts whitespace really matters. Your code var = $file is an error, since no executable var exists which knows how to process the arguments = and $file. Use

var="$file"

Instead.

To capture the output of your $file | cut -d/ -f6- pipeline you will need the following syntax:

var="$(echo $file | cut -d/ -f6-)"

In bash of recent version you can use a "here string" instead and avoid the expense of echo and the pipe.

var="$(cut -d/ -f6- <<<"$file")"

I note that you are also attempting to process the results of a find command, also with incorrect syntax. The correct syntax for this is

while IFS= read -d $'\0' -r file ; do
    var="$(cut -d/ -f6- <<<"$file")"
    echo "$var"
done < <(find "$1")

I must again question you as to what "field 6" is doing, since you've asked a similar question before.

Upvotes: 1

beny23
beny23

Reputation: 35018

Your question wasn't all that clear, but is

var=`cut -d/ -f6- < $file`

what you were after?

Upvotes: 0

Related Questions