0

I tried to assign variable a in for-loop:

#!/bin/bash

for file in `ls`
do
  a = $file
done

But when I run, it gave error:

line 5: a: command not found

Why did it give error? How to assign variable a?

3
  • 1
    Prefer $() over backticks and generally avoid parsing output of ls. Learn to use globbing a.k.a. filename expansion. Commented Dec 27, 2021 at 7:48
  • @reinardhz : This is not an assignment, but an invocation of the command named a, with = as first argument. Similarily, touch = would create a file named = and not create a variable named touch. Commented Dec 27, 2021 at 8:39
  • @user1934428 Yeah I shouldn't put spaces. Commented Dec 27, 2021 at 9:26

2 Answers 2

1

There can be no spaces on both sides of the equal sign when defining variables in the Shell.

It should be:

a=$file
Sign up to request clarification or add additional context in comments.

Comments

1

You need remove spaces i.e.

a = $file

must be

a=$file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.