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

12
  • 1
    Can't reproduce. Does which succeed? What happens if you set -ex? Commented Jan 25, 2016 at 20:58
  • 2
    avoid which Commented Jan 25, 2016 at 20:58
  • 2
    prog=$(type -P "$pro") Commented Jan 25, 2016 at 20:59
  • 1
    I just created a test script and this worked for me. Commented Jan 25, 2016 at 21:00
  • 1
    Sorry, it turns out it just wasn't working for my own scripts, not bash programs. Commented Jan 25, 2016 at 21:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 Specifically speaking about cat and alike, you're correct. Thank you for leaving a comment and improving my answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.