Reputation: 3715
I have a Bash function named "inDir" which abstracts the "go to a directory, do something, and come back to the starting directory" pattern. It is defined as:
inDir() {
if [ $# -gt 1 ]; then
local dir="$1"
local cwd=`pwd`
shift
if [ -d "$dir" ]; then
cd "$dir" && "$@"
cd "$cwd"
fi
fi
}
I am trying to create a function whose semantics don't matter much, but will essentially run:
inDir /tmp { [ -e testFile ] && touch testFile }
I hope the "implied" semantics are clear. I want to go into a directory, check if $somefile exists, and if it does, delete it. This is not working as intended. If I run:
cd
inDir /tmp [ -e testFile ] && touch testFile
it checks if testFile exists in /tmp, and then tries to touch it in ~. Can anybody think of a good way to invoke inDir so that it accepts "compound" commands?
Upvotes: 1
Views: 132
Reputation: 31451
indir() {
if [ -d "$1" ]; then
local dir="$1"
shift
(cd "$dir" && eval "$@")
fi
}
indir /tmp touch testFile
indir /tmp "[ -e testFile ] && rm testFile"
Upvotes: 3
Reputation: 798616
Nope. Just tell it to invoke a subshell.
inDir /tmp bash -c "[ -e testFile ] && touch testFile"
Upvotes: 2