1

In my terminal,

prog="cat"
name=$(which $prog)
echo $name

prints /bin/cat

But in my script:

pro="$1"
prog=$(which $pro)
echo "pro is $pro"
echo "prog is "$prog""

running scriptname cat prints

pro is cat
prog is 

How do I make which work? it should print prog is /bin/cat

user
  • 352
  • 3
  • 13
  • 1
    Can't reproduce. Does `which` succeed? What happens if you `set -ex`? – Biffen Jan 25 '16 at 20:58
  • 2
    [avoid which](http://stackoverflow.com/a/677212/418413) – kojiro Jan 25 '16 at 20:58
  • @kojiro what should I use instead to set prog to what I need? – user Jan 25 '16 at 20:59
  • 2
    `prog=$(type -P "$pro")` – kojiro Jan 25 '16 at 20:59
  • 1
    I just created a test script and this worked for me. – IT_User Jan 25 '16 at 21:00
  • Is there a similar thing to get the full path of a script I created myself? – user Jan 25 '16 at 21:02
  • 1
    Sorry, it turns out it just wasn't working for my own scripts, not bash programs. – user Jan 25 '16 at 21:03
  • 1
    If the command is on your PATH, then `type -P command` will get it. If the command is not on your PATH, then… nope, because how would the system know better than you? – kojiro Jan 25 '16 at 21:03
  • If you are insistent on using which, add the following line to your script to see what is echoed to the screen. `which $pro`[Not set as a variable] . Cannot reproduce your error but maybe that will help us see what is going on. – IT_User Jan 25 '16 at 21:03
  • In regards to your question on "is there a similar thing to get full path...", perhaps this link will help. http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?lq=1 – IT_User Jan 25 '16 at 21:06
  • I'm not trying to get the path of a script that I'm currently running. It can be any user created script. It seems like it's not possible, since there can be multiple scripts with the same name in different directories. – user Jan 25 '16 at 21:10
  • Locations you keep scripts in, you can always add to `PATH` – IT_User Jan 25 '16 at 21:18

1 Answers1

1

which(1) is an external program used to search PATH for an executable. It behaves differently on different systems and you can't rely on a useful exit code; use (from most to least portable) command -v or type -P (to find the path) or hash (to check) instead.

try printf '%s\n' "$PATH" inside your script as well as outside of it. maybe the command you're looking for is not in the PATH used in the script?

That is almost certainly the cause.

Rany Albeg Wein
  • 3,304
  • 3
  • 16
  • 26
  • Since `which` can be executed, it means `which` is in the `PATH`. It would be a very odd installation if `cat` would not be in the same directory as `which`, so it should be in the PATH too. – user1934428 Jan 26 '16 at 16:31
  • @user1934428 Specifically speaking about `cat` and alike, you're correct. Thank you for leaving a comment and improving my answer! – Rany Albeg Wein Jan 26 '16 at 16:36