質問

I want to execute some code every time cd is executed. I'm getting hung up on actually testing if cd was the last command but I think I'm on the right track. Here is what I've added to my bash_profile

update_prompt()
{
   if [ 'cd' = $1 ]; then
     #DO STUFF
   fi
}

PROMPT_COMMAND="update_prompt "$(!:0)"; $PROMPT_COMMAND"

This is close but it tries to actually execute the command in $1 rather than treat it as a string. Any ideas?

役に立ちましたか?

解決 3

I would write a shell function that wraps cd, rather than using PROMPT_COMMAND to check the last command executed:

cd () {
    builtin cd "$@"
    # CUSTOM CODE HERE
}

他のヒント

Edit: this is the solution I came up with. It's not based on the question directly, but rather on @schwiz's explanations in the comments:

update_prompt()
{
        LAST=$(history | tail -n 1 | cut -d \  -f 5)
        if [ "cd" = "$LAST" ]; then
          # DO STUFF
        fi
}

PROMPT_COMMAND="update_prompt"

Answering original question: when comparing string variable put it in parentheses to avoid interpreting:

update_prompt()
{
  if [ 'cd' = "$1" ]; then
    # ...
  fi
}

Optionally you can consider defining an alias for cd:

alias cd='echo executed && cd'

Here's a more verbose way of writing !:0 that seems to play better with PROMPT_COMMAND:

PROMPT_COMMAND='update_prompt $(history -p !:0); $PROMPT_COMMAND'.

The single quotes prevent the command substitution from happening until PROMPT_COMMAND is actually called. Technically, there is no history expansion happening; you are using the history command to process the !:0 string as an argument, which does however have the same effect as the intended history expansion.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top