Read Q
Read Q

Reputation: 1515

Bash script cannot access error while reading file

I have written a small program to get the list of all files in a directory and concatenating them to a single string variable. Here's the code

#!/bin/bash
dir ="/home/user/myfolder/abc"
res=" "

for f in $( ls $dir  ); do
    res="$res $f"
done

echo $res

However I am getting the following error

dir: cannot access =/home/user/myfolder/abc: No such file or directory

I have set all the required permissions, whats the solution?

Upvotes: 1

Views: 4592

Answers (2)

Rubens
Rubens

Reputation: 14778

Remove the space between the assignment:

#!/bin/bash
dir ="/home/user/myfolder/abc"

Do this:

#!/bin/bash
dir="/home/user/myfolder/abc"

Each language has its own syntax, and bash scripting requires no spaces between left_value=right_value during assignments; as you see, it's simply a matter of syntax.

Upvotes: 8

Gilbert
Gilbert

Reputation: 3776

likely you need:

dir=/home/user/myfolder/abc

rather than

dir ="/home/user/myfolder/abc"

The extra space after dir makes it the command "dir", which is usually aliased to ls.

Upvotes: 3

Related Questions