The problem is that which is not storing the path to the program.
#!/bin/bash
read -p "Enter progam name: " name
path=which $name
nano $path
The problem is that which is not storing the path to the program.
#!/bin/bash
read -p "Enter progam name: " name
path=which $name
nano $path
path=which $name
This isn't the syntax you need. This invokes a command stored in $name
with a variable path=which
added to its environment. If you'd quoted it, as in path="which $name"
you'd instead set path
in your environment, but it would contain the string which ...
(where ... is the value of $name
).
What you're looking for is command substitution, which allows you to capture the output of a command. So instead you should do:
path="$(which "$name")"
This will set path
to the result of which "$name"
, which is what you want.
As suggested in the comments you can skip the path
variable entirely and just say:
nano "$(which "$name")"
You can even skip this script entirely assuming you don't mind remembering the syntax, and just entering:
$ nano "$(which command-to-look-at)"
Directly in the prompt.
Going the other way, if you want something more robust you can avoid opening binary files with something like this (notice it's a function rather than a script, you can add it to your .bashrc
directly or pull out the body into a separate script if you prefer):
inspect_command() {
local name="${1:?No command provided}"
local path
path=$(which "$name") || {
echo "No command '$name' found"
return 1
}
if [[ "$(file --brief --mime-encoding "$path")" == "binary" ]]; then
echo "$path appears to be a binary file."
local response;
read -p "Are you sure you'd like to continue? [y/N] " response;
[[ "$response" =~ ^([yY][eE][sS]|[yY])$ ]] || return 0
fi
"${EDITOR:-nano}" "$path"
}
This behaves the same as above on text files (though you pass the command as an argument, and it uses your preferred EDITOR
if one is set), but warns you before attempting to open binary files.
$ inspect_command curl
/usr/bin/curl appears to be a binary file.
Are you sure you'd like to continue? [y/N] n
$ inspect_command some_script.sh
... opens nano
Use find
instead of which
.
path=$(find /some/base/path -type f -name "${name}")