在 Screen 和 ZSH 中加载 RVM 环境

在 Screen 和 ZSH 中加载 RVM 环境

这个话题已经让我抓狂了一段时间了,我希望能够找出问题所在。我在终端中使用zshwithscreen已经有一段时间了。但是,无论出于什么原因,似乎在登录时,我的安装RVM不会默认加载。Ruby 正确设置为 RVM 安装的版本 (1.9.3),但其余环境不会加载:

~/Desktop => ruby -v
ruby 1.9.3p0 (2011-10-30 revision 33570) [x86_64-darwin11.2.0]
~/Desktop => rails -v
Rails is not currently installed on this system. To get the latest version, simply type:

    $ sudo gem install rails

You can then rerun your "rails" command.
~/Desktop => rvm reload
RVM reloaded!
~/Desktop => rails -v
Rails 3.2.1

我不知道出了什么问题,而且从各方面来看,似乎没有什么问题。我的screenrc文件正确地使用了带有 的登录 shell shell -$SHELL,但似乎没有任何效果(不幸的是,这似乎是唯一修复了其他人在 中安装 RVM 的问题的东西screen,而且这是文档建议您确保已设置的,但对我来说似乎没什么区别)。

我在 Mac OS X 10.7.3 上运行,我的登录 shell 设置为/bin/zsh。我不使用oh-my-zsh。我的zshrc文件如下(抱歉太长了——我肯定不是全部其中有些是相关的,但我不想遗漏任何可能有用的信息):

# -----------------------------------------------
# Screen
# -----------------------------------------------

if [[ $TERM != 'screen' ]]; then
  exec screen -aADRU
fi

# -----------------------------------------------
# Startup Scripts
# -----------------------------------------------

[[ -s ~/.rvm/scripts/rvm ]] && source ~/.rvm/scripts/rvm
cd ~/Desktop

# -----------------------------------------------
# Environment Variables
# -----------------------------------------------

export HISTFILE=~/.zsh_history
export HISTSIZE=10000
export HISTCONTROL=ignoredups
export SAVEHIST=10000

export PATH=.:~/.rvm/bin:/usr/local/bin:/usr/local/sbin:~/Library/Haskell/bin:/usr/local/narwhal/bin:/bin:/sbin:/usr/bin:/usr/local/share:/usr/sbin:/usr/local/texlive/2011/bin/universal-darwin
export CC=/usr/bin/clang
export EDITOR='vim'
export GIT_EDITOR="mate --name 'Git Commit Message' -wd -l 1"
export LC_TYPE=en_US.UTF-8
export CLICOLOR=AxFxcxdxBxegbdHbGgcdBd
export NODE_PATH=/usr/local/lib/node/:$NODE_PATH
export CAPP_BUILD="/Users/itaiferber/Desktop/Cappuccino Build"
export NARWHAL_ENGINE=jsc

# -----------------------------------------------
# Prompt
# -----------------------------------------------

## Root Prompt
[ $UID = 0 ] && export PROMPT="%~ +=> " && export RPROMPT="%*"

## General Prompt
[ $UID != 0 ] && export PROMPT="%~ => " && export RPROMPT="%*"

# -----------------------------------------------
# Aliases
# -----------------------------------------------

## Command Aliases
alias ..='cd ..'
alias ...='cd ../..'
alias internet='lsof -P -i -n | cut -f 1 -d " " | uniq'
alias restart='sudo shutdown -r NOW'
alias ls='ls -AFGp'
alias tree='tree -alCF --charset=UTF-8 --du --si'
alias zshrc='$=EDITOR ~/.zshrc && source ~/.zshrc'
alias rake='noglob rake'

## Root Aliases
[ $UID = 0 ] &&       \
  alias rm='rm -i' && \
  alias mv='mv -i' && \
  alias cp='cp -i'

# -----------------------------------------------
# User-defined Functions
# -----------------------------------------------

# Usage: rm <file>
# Description: move files to trash instead of deleting them outright.
# Note: this will move files to the trash as long as no flags are set.
#       If a flag is encountered, it will rm the files normally.
rm () {
  local path
  for path in "$@"; do
    if [[ "$path" = -* ]]; then
      /bin/rm $@
      break
    else
      local dst=${path##*/}
      while [ -e ~/.Trash/"$dst" ]; do
        dst="$dst "$(/bin/date +%H-%M-%S)
      done
      /bin/mv "$path" ~/.Trash/"$dst"
    fi
  done
}

# Usage: extract <file>
# Description: extracts archived files / mounts disk images.
# Note: .dmg/hdiutil is Mac OS X-specific.
extract () {
  if [ -f $1 ]; then
    case $1 in
      *.tar.bz2)  tar -jxvf $1      ;;
      *.tar.gz)   tar -zxvf $1      ;;
      *.bz2)      bunzip2 $1        ;;
      *.dmg)      hdiutul mount $1  ;;
      *.gz)       gunzip $1         ;;
      *.tar)      tar -xvf $1       ;;
      *.tbz2)     tar -jxvf $1      ;;
      *.tgz)      tar -zxvf $1      ;;
      *.zip)      unzip $1          ;;
      *.Z)        uncompress $1     ;;
      *)          echo "'$1' cannot be extracted/mounted via extract()." ;;
    esac
  else
    echo "'$1' is not a valid file."
  fi
}

# Usage: pman <manpage>
# Description: opens up the selected man page in Preview.
pman () {
  man -t $@ | open -f -a /Applications/Preview.app
}

# Usage: pid <processname>
# Description: returns the pid of the first process with the given name.
pid () {
  ps Ao pid,comm | grep -im1 $1 | awk '{match($0,/([0-9]+)/); print substr($0,RSTART,RLENGTH);}'
}

# Usage: relaunch <appname>
# Description: quits and relaunches the app with the given name.
relaunch () {
  kill `pid $1`; open -a $1
}

# Usage: inject <processname>
# Description: uses StarInject to inject code into the first process with the given name.
inject () {
  StarInject `pid $1`
}

# Usage: fp <name>
# Description: find and list processes matching a case-insensitive partial-match string.
fp () {
  ps Ao pid,comm | awk '{match($0,/[^\/]+$/); print substr($0,RSTART,RLENGTH)": "$1}' | grep -i $1 | grep -v grep
}

# Usage: fk <name>
# Description: find and kill a process matching a case-insensitive partial-match string.
fk () {
  IFS=$'\n'
  PS3='Kill which process? (1 to cancel): '
  select OPT in "Cancel" $(fp $1); do
    if [ $OPT != "Cancel" ]; then
      kill $(echo $OPT|awk '{print $NF}')
    fi
    break
  done
  unset IFS
}

# Usage: console <processname>
# Description: get the latest logs for the given process names.
console () {
  if [[ $# > 0 ]]; then
    query=$(echo "$*"|tr -s ' ' '|')
    tail -f /var/log/system.log | grep -i --color=auto -E "$query"
  else
    tail -f /var/log/system.log
  fi
}

# Usage: create <file>
# Description: creates and opens a file for editing.
create () {
  touch $1 && $=EDITOR $1
}

# Usage: reset
# Description: 'resets' the terminal by changing the current working directory
# to the desktop and clearing the screen.
reset () {
  cd ~/Desktop && clear
}

# -----------------------------------------------
# zsh Options
# -----------------------------------------------

# Directories
setopt              \
  AUTO_CD           \
  AUTO_PUSHD        \
  CD_ABLE_VARS      \
  CHASE_DOTS        \
  CHASE_LINKS

# Completion
setopt              \
  AUTO_LIST         \
  AUTO_MENU         \
  AUTO_PARAM_SLASH  \
  COMPLETE_IN_WORD  \
  LIST_TYPES        \
  MENU_COMPLETE     \
  REC_EXACT

# History
setopt              \
  APPEND_HISTORY    \
  EXTENDED_HISTORY

# Input/Output
setopt              \
  CORRECT

# Scripts and Functions
setopt              \
  MULTIOS

# Other
setopt              \
  NO_BEEP           \
  ZLE

# Key Bindings
bindkey "^[[3~" delete-char

# -----------------------------------------------
# zsh Autocompletion
# -----------------------------------------------

# Turn on auto-completion.
autoload -U compinit && compinit -C && autoload -U zstyle+

# Attempt to complete as much as possible.
zstyle ':completion:*' completer _complete _list _oldlist _expand _ignored _match _correct
zstyle ':completion:*::::' completer _expand _complete _ignored _approximate

# Sort files by name.
zstyle ':completion:*' file-sort name

# Allow for case-insensitive completion.
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

# Color completions.
zstyle ':completion:*' list-colors ${LSCOLORS}
zstyle ':completion:*:*:kill:*:processes' command 'ps -axco pid,user,command'
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'

# Set the amount of completions that triggers the menu.
zstyle ':completion:*' menu select=long

# Ignore certain patterns.
zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~'
zstyle ':completion:*:*:(^rm):*:*files' ignored-patterns '*?.(o|c~|old|pro|zwc)'

# Cache completions.
zstyle ':completion::complete:*' use-cache 1
zstyle ':completion::complete:*' cache-path ~/.zcompcache/$HOST

# Allow errors.
zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/2 )) numeric )'

# Insert all expansions for expand completer (eh, don't know what this does).
zstyle ':completion:*:expand:*' tag-order all-expansions

# Formatting and messages.
zstyle ':completion:*' list-prompt '%SAt %p: Hit TAB for more, or the character to insert%s'
zstyle ':completion:*' verbose yes
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'
zstyle ':completion:*' group-name ''

# Offer indexes before parameters in subscripts.
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters

另外我的screenrc文件如下:

# Use login shell.
shell -$SHELL

# Don't display the copyright page.
startup_message off

# Escapes the 'z' character, instead of 'c'.
escape ^Zz

# Set up the tab bar.
caption always              "%?%F%{=u ..}%? %h %-024=%{+b}"
hardstatus alwayslastline   "%{= ..} %-w%{=b ..} %n* %t %{-}%+w %=%{= ..}"

然而,最奇怪的是,当我将 RVM 源代码行更改为 时[[ -s ~/.rvm/scripts/rvm ]] && source ~/.rvm/scripts/rvm && rvm reload,我看到了消息RVM reloaded!,但环境仍然尚未设置。rails直到我再次重新加载 RVM 才能识别。

任何帮助都将不胜感激。谢谢!

答案1

经过一番调整后,rvm终于成功默认加载了其环境。现在,我不知道我所做的哪一部分修复了这个问题,但希望这对某些人有帮助。

zsh本质上,我仔细研究了一下,将我的配置拆分为两个文件:.zshenv文件(由所有程序加载)和.zshrc文件(由图形程序加载)。对于那些不熟悉其zsh工作原理的人来说,这些文件本质上类似于.bash_profile.bashrc

我的.zshenv

# -------------------------------------------------------------
# Maintainer: Itai Ferber
#             http://itaiferber.net - [email protected]
#
# Version: 1.0 - 19/02/12
#
# Sections:
# -> RVM
# -> Environment Variables
# -> Aliases
# -> File Manipulation
# -> Process Manipulation
# -> Terminal Manipulation
# -> zsh Options
#
# Revisions:
# -> 1.0.0: Initial revision (settings copied over from .zshrc where logical).
# -------------------------------------------------------------

# -------------------------------------------------------------
# => RVM
# -------------------------------------------------------------
[[ -s ~/.rvm/scripts/rvm ]] && source ~/.rvm/scripts/rvm

# -------------------------------------------------------------
# => Environment Variables
# -------------------------------------------------------------
# Path
export PATH=.:~/.rvm/bin:/usr/local/bin:/usr/local/sbin:~/Library/Haskell/bin:/usr/local/texlive/2011/bin/universal-darwin:/usr/local/narwhal/bin:$PATH

# History
export HISTFILE=~/dotfiles/.zsh_history
export HISTSIZE=10000
export HISTCONTROL=ignoredups
export SAVEHIST=10000

# Editor
export EDITOR=vim

# Localization
export LC_TYPE=en_US.UTF-8

# Frameworks
export NODE_PATH=/usr/local/lib/node/:$NODE_PATH
export CAPP_BUILD='/Users/itaiferber/Desktop/Cappuccino Build'
export NARWHAL_ENGINE=jsc

# -------------------------------------------------------------
# => Aliases
# -------------------------------------------------------------
# Command Aliases
alias ..='cd ..'
alias ...='cd ../..'
alias internet='lsof -inP | cut -f 1 -d " " | uniq'
alias restart='sudo shutdown -r NOW'

# Expansions
alias ls='ls -AFGp'
alias tree='tree -aCFl --charset=UTF8 --du --si'

# Root Aliases
[ $UID = 0 ] && \
    alias rm='rm -i' && \
    alias mv='mv -i' && \
    alias cp='cp -i'

# -------------------------------------------------------------
# => Terminal Manipulation
# -------------------------------------------------------------
# Usage: reset
# Description: 'resets' the terminal by clearing and returning to default directory
reset () {
    cd ~/Desktop && clear
}

# -------------------------------------------------------------
# => Process Manipulation
# -------------------------------------------------------------
# Usage: pid <procname>
# Description: returns the pid of the process with the given name
# Notes: if multiple processes with the given name are running, no guarantee is made to which pid is returned
pid () {
    ps Ao pid,comm | grep -im1 $1 | awk '{match($0,/([0-9]+)/); print substr($0,RSTART,RLENGTH);}'
}

# Usage: fp <pattern>
# Description: list processes matching the given partial-match pattern
fp () {
    ps Ao pid,comm | awk '{match($0,/[^\/]+$/); print substr($0,RSTART,RLENGTH)": "$1}' | grep -i $1 | grep -v grep
}

# Usage: fk <pattern>
# Description: list process matching the given partial-match pattern to kill
fk () {
    IFS=$'\n'
    PS3='Kill which process? (1 to cancel): '
    select OPT in 'Cancel' $(fp $1); do
        if [ $OPT != 'Cancel' ]; then
            kill $(echo $OPT | awk '{print $NF}')
        fi
        break
    done
    unset IFS
    unset PS3
}

# Usage: console <procname>
# Description: get the latest logs for the given process name
console () {
    if [[ $# > 0 ]]; then
        query=$(echo "$*" | tr - s ' ' '|')
        tail -f /var/log/system.log | grep -i --color=auto -E "$query"
    else
        tail -f /var/log/system.log
    fi
}

# -------------------------------------------------------------
# => File Manipulation
# -------------------------------------------------------------
# Usage: rm <file>
# Description: if called with no arguments, move files to trash instead of deleting outright
rm () {
    local path
    for path in "$@"; do
        if [[ "$path" = -* ]]; then
            /bin/rm $@
            break
        else
            local file=${path##*/}
            while [ -e ~/.Trash/"$file" ]; do
                file="$file "$(date +%H-%M-%S)
            done
            /bin/mv "$path" ~/.Trash/"$file"
        fi
    done
}

# Usage: extract <file>
# Description: extracts archived files / mounts disk images
extract () {
    if [ -f $1 ]; then
        case $1 in
            *.bz2) bunzip2 $1;;
            *.dmg) hdiutil mount $1;;
            *.gz) gunzip $1;;
            *.tar) tar -xvf $1;;
            *.tar.bz2|*.tbz2) tar -jxvf $1;;
            *.tar.gz|*.tgz) tar -zxvf $1;;
            *.zip) unzip $1;;
            *.Z) uncompress $1;;
            *) echo "'$1' not recognized.";;
        esac
    else
        echo "'$1' not found."
    fi
}

# -------------------------------------------------------------
# => zsh Options
# -------------------------------------------------------------
# Directories
setopt AUTO_CD AUTO_PUSHD CD_ABLE_VARS CHASE_DOTS CHASE_LINKS

# Completion
setopt AUTO_LIST AUTO_MENU AUTO_PARAM_SLASH COMPLETE_IN_WORD LIST_TYPES MENU_COMPLETE REC_EXACT

# History
setopt APPEND_HISTORY EXTENDED_HISTORY

# Input/Output
setopt CORRECT

# Scripts and Functions
setopt MULTIOS

# Other
setopt NO_BEEP ZLE

# Key Bindings
bindkey "^[[3~" delete-char

我的.zshrc

# -------------------------------------------------------------
#  Maintainer: Itai Ferber
#              http://itaiferber.net - [email protected]
#
#  Version: 1.0 - 19/02/12
#
#  Sections:
#  -> zshenv
#  -> screen
#  -> Environment Variables
#  -> Prompt
#  -> zsh Autocompletion
#
#  Revisions:
#  -> 1.0.0: Initial revision. Style copied from vimrc.
# -------------------------------------------------------------

# -------------------------------------------------------------
# => zshenv
# -------------------------------------------------------------
source ~/.zshenv

# -------------------------------------------------------------
# => screen
# -------------------------------------------------------------
if [[ $TERM != 'screen' ]]; then
    exec screen -aADRU
fi

reset

# -------------------------------------------------------------
# => Environment Variables
# -------------------------------------------------------------
export TERM=xterm-256color
export CLICOLOR=AxFxcxdxBxegbdHbGgcdBd

# -------------------------------------------------------------
# => Prompt
# -------------------------------------------------------------
if [[ $UID = 0 ]]; then
    export PROMPT="%~ +=> "
else
    export PROMPT="%~ => "
fi

export RPROMPT="%*"

# -------------------------------------------------------------
# => zsh Autocompletion
# -------------------------------------------------------------
# Enable autocompletion.
autoload -U compinit && compinit -C && autoload -U zstyle+

# Attempt to complete as much as possible.
zstyle ':completion:*' completer _complete _list _oldlist _expand _ignored _match _correct
zstyle ':completion:*::::' completer _expand _complete _ignored _approximate

# Sort files by name.
zstyle ':completion:*' file-sort name

# Allow for case-insensitive completion.
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

# Color completions.
zstyle ':completion:*' list-colors ${CLICOLOR}
zstyle ':completion:*:*:kill:*:processes' command 'ps -axco pid,user,command'
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'

# Set the amount of completions that triggers the menu.
zstyle ':completion:*' menu select=long

# Ignore certain patterns.
zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~'
zstyle ':completion:*:*:(^rm):*:*files' ignored-patterns '*?.(o|c~|old|pro|zwc)'

# Cache completions.
zstyle ':completion::complete:*' use-cache 1
zstyle ':completion::complete:*' cache-path ~/.zcompcache/$HOST

# Allow errors.
zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/2 )) numeric )'

# Insert all expansions for expand completer (eh, don't know what this does).
zstyle ':completion:*:expand:*' tag-order all-expansions

# Formatting and messages.
zstyle ':completion:*' list-prompt '%SAt %p: Hit TAB for more, or the character to insert%s'
zstyle ':completion:*' verbose yes
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*:messages' format '%d'
zstyle ':completion:*:warnings' format 'No matches for: %d'
zstyle ':completion:*:corrections' format '%B%d (errors: %e)%b'
zstyle ':completion:*' group-name ''

# Offer indexes before parameters in subscripts.
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters

希望这可以作为一个小指南,为遇到与我相同问题的人提供指导。

答案2

这是一个巨大的黑客攻击,但我只是把这一行放入.bashrc以及.bash_profile

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function* 

有了这个,rvm use 1.93类似的命令在正常和屏幕提示下都可以工作,不再给出错误rvm is not a function。只要这个代码片段是幂等的(即不会因调用两次或 N 次而产生不良影响),这应该没问题。而且考虑到它无论如何都会在每个登录 shell 上调用,这可能是真的。但让我们看看情况是否如此……

相关内容