MacOS – How to use ls command with a variable for a directory in zsh

environment-variablesmacosterminalzsh

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?

Best Answer

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