I am trying to write a simple utility function in Bash, which will perform an “action” in the given directory. So I am basically abstracting the “go to a directory, do something, and come back” pattern.
inDir() {
if [$# -le 1]; then
return;
else
local dir="$1";
local action="$2";
local cwd=`pwd`;
if [ -d "$dir" ]; then
cd "$dir";
$action;
cd "$cwd";
else
return;
fi
fi
}
Unfortunately, I get what I think is a spurious error when I run this, and I’m not sure where it is coming from. For example:
$ inDir "/tmp" "touch hi"
correctly creates the file /tmp/hi, but also gives the error:
[2: command not found
I’m not sure if this matters to reading the error, but my prompt starts off with a “[“.
Any help?
Despite what it might look like, ‘[‘ is actually a command called
test, so:should be:
Note the space between the ‘[‘ and the next bit of code. Without it, the code reads as
which I think is obviously wrong. You also need a space before the closing square-bracket, which isn’t a command, but is a delimiter.