0

I set a variable named $G2_HW_sci. This is the output with echo.

user@192 SS % echo $G2_HW_sci                              
~/Documents/trabalho/SS/G2/science/homework/student_work/

Then I tried to access the contents of this folder with ls but I am getting this error:

user@192 SS % ls $G2_HW_sci
ls: ~/Documents/trabalho/SS/G2/science/homework/: No such file or directory

user@192 SS % ls "$G2_HW_sci"                                          
ls: ~/Documents/trabalho/SS/G2/science/homework/: No such file or directory

user@192 SS % ls "${G2_HW_sci}"
ls: ~/Documents/trabalho/SS/G2/science/homework/student_work/: No such file or directory

user@192 SS % ls $"G2_HW_sci"
ls: $G2_HW_sci: No such file or directory

Now, if I just use ls with the absolute path to the directory it works:

user@192 SS % ls ~/Documents/trabalho/SS/G2/science/homework/student_work
2A          G2C_johnny.jpg      G2D_leonidas_1.jpg
2B          G2C_boris.jpg       G2E_angeline_1.jpg
2C          G2D_hellen_1.pdf        other
G2C_jerry_1.jpeg    G2D_leonidas_1.2.jpg

Another option that works is: echo $G2_HW_sci | ls

I read some materials around here but they all seem to be using bash and by trying their solutions it didn't work for me.

I believe it may have something to do with the fact that I'm using zsh instead of bash.

What can I do to see the contents of the folder with the ls command?

2

You don't show how you assign the variable in the first place, but usually issues with ~ in variables come from the way you quote (or don't quote) during assignment. To make it work you need to omit quotes when assigning ~ to a variable.

$ foo=~
$ echo $foo
/Users/pse
$ foo="~"
$ echo $foo
~
$ ls $foo
ls: ~: No such file or directory
2
  • I assigned it using G2_HW_sci="~/Documents/trabalho/SS/G2/science/homework/student_work/" Apr 3 '20 at 0:33
  • Thanks for the tip, now I know to make it work! Apr 3 '20 at 0:34
0

I found out what the problem was. I was using a relative path with the ~.

I used the absolute path and it worked.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .