Reputation: 3799
I have a script in one of my application folders.Usually I just cd
into that locatin in Unix box and run the script e.g.
UNIX> cd My\Folder\
My\Folder> MyScript
This prints the required result.
I am not sure how do I do this in Bash script.I have done the following
#!/bin/bash
mydir=My\Folder\
cd $mydir
echo $(pwd)
This basically puts me in the right folder to run the required script . But I am not sure how to run the script in the code?
Upvotes: 0
Views: 139
Reputation: 70381
If you can call MyScript
(as opposed to ./MyScript
), obviously the current directory (".") is part of your PATH. (Which, by the way, isn't a good idea.)
That means you can call MyScript
in your script just like that:
#!/bin/bash
mydir=My/Folder/
cd $mydir
echo $(pwd)
MyScript
As I said, ./MyScript
would be better (not as ambiguous). See Michael Wild's comment about directory separators.
Generally speaking, Bash considers everything that does not resolve to a builtin keyword (like if
, while
, do
etc.) as a call to an executable or script (*) located somewhere in your PATH. It will check each directory in the PATH, in turn, for a so-named executable / script, and execute the first one it finds (which might or might not be the MyScript
you are intending to run). That's why specifying that you mean the very MyScript
in this directory (./
) is the better choice.
(*): Unless, of course, there is a function of that name defined.
Upvotes: 2
Reputation: 3938
#!/bin/bash
mydir=My/Folder/
cd $mydir
echo $(pwd)
MyScript
Upvotes: 2
Reputation: 26381
Your nickname says it all ;-)
When a command is entered at the prompt that doesn't contain a /
, Bash first checks whether it is a alias or a function. Then it checks whether it is a built-in command, and only then it starts searching on the PATH
. This is a shell variable that contains a list of directories to search for commands. It appears that in your case .
(i.e. the current directory) is in the PATH
, which is generally considered to be a pretty bad idea.
If the command contains a /
, no look-up in the PATH
is performed. Instead an exact match is required. If starting with a /
it is an absolute path, and the file must exist. Otherwise it is a relative path, and the file must exist relative to the current working directory.
So, you have two acceptable options:
Put your script in some directory that is on your PATH
. Alternatively, add the directory containing the script to the PATH
variable.
Use an absolute or relative path to invoke your script.
Upvotes: 1
Reputation: 22094
I would rather put the name in quotes. This makes it easier to read and save against mistakes.
#!/bin/bash
mydir="My Folder"
cd "$mydir"
echo $(pwd)
./MyScript
Upvotes: 1