You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从目录栈中的目录复制文件至当前目录,是否有更优方案?

Better Ways to Copy Files from the Last Directory in Your Directory Stack

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 DIRSTACK or Zsh’s shorthand uses shell built-ins instead of spawning dirs and tail processes.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:27:11