I wish to accomplish the following:
If I execute "cd production" on bash prompt, I should go into the directory and a message should be displayed "You are in production", so that the user gets warned.
I wish to accomplish the following:
If I execute "cd production" on bash prompt, I should go into the directory and a message should be displayed "You are in production", so that the user gets warned.
You can do it by executing the following in the shell context (e.g., .bashrc).
xcd() {
if [[ "$1" == "production" ]] ; then
echo Warning, you are in production.
fi
builtin cd $1
}
alias cd=xcd
This creates a function then aliases the cd
command to that function. The function itself provides the warning then calls the real cd
.
A better solution, however, may be to detect real paths, since the solution you've asked for will give you a false positive for "cd $HOME ; cd production"
and false negative for "cd /production/x"
(if /production
was indeed the danger area).
I would do something like:
#!/bin/bash
export xcd_warn="/home/pax /tmp"
xcd() {
builtin cd $1
export xcd_path=$(pwd)
for i in ${xcd_warn} ; do
echo ${xcd_path}/ | grep "^${i}/"
if [[ $? -eq 0 ]] ; then
echo Warning, you are in ${i}.
fi
done
}
alias cd=xcd
which will allow you to configure the top-level danger directories as absolute paths.
Don't do it that way. :)
What you really want to know isn't whether the user just got into the 'production' directory via a cd command; what you really want to know is if you're modifying production data, and how you got there (cd, pushd, popd, opening a shell from a parent process in that directory already) is irrelevant.
It makes much more sense, then, to have your shell put up an obnoxious warning when you're in the production directory.
function update_prompt() {
if [[ $PWD =~ /production(/|$) ]] ; then
PS1="\u@\h \w [WARNING: PRODUCTION] $"
else
PS1="\u@\h \w $"
fi
}
PROMPT_COMMAND=update_prompt
Feel free to replace the strings in question with something much more colorful.