Linux环境下如何修改Ruby Gem目录位置?迁移~/.gems至/opt/Ruby
Hey there! Let's walk through this process step by step—first moving your existing gem folder safely, then configuring Ruby to install future gems to the new location by default.
Step 1: Migrate the Existing ~/.gems Folder
First, we'll get your current gems over to /opt/Ruby without breaking anything:
- Create the target directory (if it doesn't already exist):
sudo mkdir -p /opt/Ruby - Copy your .gems folder to the new location, preserving file permissions and structure:
sudo cp -r ~/.gems /opt/Ruby/ - Fix ownership so your user has full access to the migrated folder (this prevents permission errors later):
sudo chown -R $USER:$USER /opt/Ruby/.gems - Backup the original folder (optional but highly recommended, just in case you need to roll back):
mv ~/.gems ~/.gems.bak
Step 2: Update Ruby Gem's Default Installation Path
There are two reliable ways to set this up—pick whichever fits your workflow better:
Option 1: Use Environment Variables (Recommended for Flexibility)
This method works across most shell environments (Bash, Zsh, etc.). Add these lines to your shell's config file (~/.bashrc for Bash, ~/.zshrc for Zsh):
# Point Gem to the new location export GEM_HOME="/opt/Ruby/.gems" export GEM_PATH="/opt/Ruby/.gems" # Add gem binaries to your system PATH so you can run them directly export PATH="$GEM_HOME/bin:$PATH"
To apply the changes immediately without logging out:
# For Bash source ~/.bashrc # For Zsh source ~/.zshrc
Option 2: Use gem config (Global Gem Settings)
If you prefer setting it directly via Ruby's gem tool, run these commands:
gem config set home /opt/Ruby/.gems gem config set path /opt/Ruby/.gems
Verify the Changes
To make sure everything is working correctly, run:
gem env
Look for the GEM HOME and GEM PATH lines—they should both point to /opt/Ruby/.gems.
You can also test installing a small gem to confirm:
gem install hello-world
Check that the gem files appear in /opt/Ruby/.gems/gems/hello-world-*.
Note for Version Manager Users
If you're using RVM, rbenv, or another Ruby version manager, you might need to adjust their specific config files instead:
- RVM: Add the environment variables to
~/.rvmrcor your project's.rvmrc - rbenv: Use
rbenv varsto set theGEM_HOME/GEM_PATHvariables
内容的提问来源于stack exchange,提问作者user8664650

