Teddy13
Teddy13

Reputation: 3854

setting variable Linux

I am new to linux shell scripting and I am trying to set the following variable to get the size of a folder path passed in from keyboard. I keep getting an error saying invalid option. T

Can anyone tell me what I am doing wrong? The error disappears when I remove the "size" variable and leave it as is.

Thanks!

#!/bin/bash 
echo -e "\nEnter the first directory (relative path)"
read dir1

size=find $dir1 -type f | wc -l 

 echo $size

Upvotes: 0

Views: 1162

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64308

It should be:

size=$(find $dir1 -type f | wc -l)

Using the $() notation means that a command should be run and its output placed on the line.

This is because variables are assigned literal text values.

myvar=foo

will put the string "foo" into myvar and not the value of the variable foo or the result of the foo command.

myvar=$foo

will put the value of the variable foo into myvar. And

myvar=$(foo)

will put the result of running the command foo into myvar.

There is a special part of the shell syntax that lets you assign variable values before running a command, and those variable values are only set for that one command. It looks like this:

x=foo1 y=foo2 command parameter ...

The way you have written your line

size=find $dir1 -type f | wc -l 

size is assigned a value of "find", then

$dir1 -type f  # this won't be a valid command

is executed as a separate command.

Upvotes: 3

Related Questions