2

I am writing my own unix scripts so I want to add a new directory for Bash. I add sth in .bash_profile like this.

PATH="~/Documents:${PATH}"
export PATH

and in my ~/Documents, there is a file named test of which the content is

#!/usr/bin/env python3.5
print("hahahhah")

I also used

chmod 755 test

to make it executable.

But I cannot call it in terminal directly. ./test works as usual. What went wrong?

After I change to

PATH="$HOME/Documents:${PATH}"
export PATH

nothing happens.

FDSM_lhn@9-53:~/Documents$ test
FDSM_lhn@9-53:~/Documents$ ./test
hahahhah

Solution: The fundamental reason is that I have a command of the same name as default one, So it won't work any way! Changing name will be sufficient!

Li haonan
  • 600
  • 1
  • 6
  • 24
  • What's in PATH? Does `~/Documents` appear, or the expanded version? Unless it's the expanded version, it won't help, and I think the double quotes prevent the `~` being expanded. Add `echo "$PATH"` after the `export PATH` and see what it says. – Jonathan Leffler Nov 11 '15 at 03:37

1 Answers1

5

Tilde doesn't get expanded inside strings. So by quoting the right-hand side of the assignment you prevent it from being expanded and get a literal ~ in your PATH variable which doesn't help you any.

You have two ways to fix this:

  1. Drop the quotes on the assignment (yes this is safe, even for $PATH values with spaces, etc.).

  2. Use $HOME instead of ~.

I prefer the second solution but the first is entirely valid for this case.

Beware though that in places where you aren't doing a straight assignment you often cannot just drop the quotes and trying to use ~ will cause problems.

In which case you will end up finding a question like this with an answer like this and something ugly like this.

Community
  • 1
  • 1
Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • 3
    And of course, shadowing the system command `test` with your own unrelated program is always a bad idea. – tripleee Nov 11 '15 at 04:51
  • ```PATH="$HOME/Documents:${PATH}" export PATH``` is still not working. Do I need to restart the whole computer? – Li haonan Nov 11 '15 at 07:19
  • No, but you need to do that in the shell session you are testing or load a new shell session (assuming you put that in a shell startup file). What does `declare -p PATH` say when it isn't working? – Etan Reisner Nov 11 '15 at 13:38
  • Oh man, the first comment help me out. The command ```test``` shadow my own test program. – Li haonan Nov 25 '15 at 07:58