Reputation: 113
I've been working on a small script that opens gedit or whatever editor I have in my Linux box to edit another script that is in a folder that is included in the PATH
variable.
I am using which
to find the path of the script so that I can give the path to the editor and start editing that script. The name of the script is obviously the first argument of the script.
The problem is that which
cannot find the script when it is given as the first argument of another script, but it will find the path if I use it directly.
Here is an example to make it clearer.
which script.sh
prints "/home/bla/bla/script_folder/script.sh
but if I use that in a script like so:
echo "ScriptPath: $(which 1)"
echo "ScriptName: $1"
This won't work for some weird reason. I do know the location for the script used in argument 1 is available in my PATH variable. Echo
will not print anything when I give it $(which 1)
, assuming $1
is the name of the script I am looking for. I have no idea why this is. Then I decided to put the name of the script in a variable and then use which to find whatever that new variable contains (in my case the name of the script), but it won't work either.
Ex:
scriptName="$1"
echo "$(which scriptName)"
This won't work either.
Such a simple thing, and I cannot make it work for some weird reason. Any ideas why this is not working?
Upvotes: 0
Views: 614
Reputation: 125838
As @glenn jackman commented: you need to use $
to reference variables, even inside $( )
. Thus, the command echo "ScriptPath: $(which 1)"
looks for a command named "1". What you want is echo "ScriptPath: $(which "$1")"
(note that wrapping variable references like $1
in double-quotes is almost always a good idea). Similarly:
scriptName="$1"
echo "$(which scriptName)" # doesn't work, looks for a command named "scriptName"
echo "$(which "$scriptName")" # works as expected
Upvotes: 1
Reputation: 167
I'm pretty sure you have it wrong with $(which 1) where you need to put the command that you want to run inside backticks: `which $1`
echo "Script Path: `which $1`"
echo "Script Name: $1"
Upvotes: 0