从目录栈中的目录复制文件至当前目录,是否有更优方案?
Great question! Your current command works, but it relies on spawning subshells (dirs, tail) and can break if the directory path contains spaces or special characters. Let’s look at cleaner, more robust alternatives:
1. Use Bash’s Built-in DIRSTACK Array
Bash maintains the directory stack in the DIRSTACK array, where the last entry (most recently pushed directory) is ${DIRSTACK[-1]}. This avoids external processes entirely and handles paths with spaces safely when quoted:
cp "${DIRSTACK[-1]}"/somefile.txt ./
If you want to keep the same filename in the current directory, you can even omit the explicit target—cp will default to the current directory:
cp "${DIRSTACK[-1]}"/somefile.txt .
2. Create a Reusable Function (For Frequent Use)
Since you do this often, wrapping the logic in a shell function makes it even easier. Add this to your ~/.bashrc or ~/.zshrc:
cp_from_last_stack() { # Check if at least a source file is provided if [[ $# -eq 0 ]]; then echo "Usage: cp_from_last_stack <source-file> [destination-file]" return 1 fi local source_path="${DIRSTACK[-1]}"/"$1" # Use the source filename as default if no destination is given local dest_path="${2:-./$1}" cp "$source_path" "$dest_path" }
Now you can run it with just:
# Copy somefile.txt from last stack dir to current dir (same name) cp_from_last_stack somefile.txt # Copy and rename to newfile.txt cp_from_last_stack somefile.txt newfile.txt
3. Zsh-Specific Shortcut (If You Use Zsh)
Zsh has shorthand for directory stack entries: ~+$#dirstack points to the last directory in the stack. So you can write:
cp ~+$#dirstack/somefile.txt .
Why These Are Better Than Your Original Command
- No subshell overhead: Using
DIRSTACKor Zsh’s shorthand uses shell built-ins instead of spawningdirsandtailprocesses. - Space-safe: Quoting the paths ensures directories with spaces (e.g.,
My Documents) don’t cause errors. - Reusability: The function turns a long command into a simple, memorable call.
内容的提问来源于stack exchange,提问作者Melandru's Square

