如何将shell读取命令的路径传递到wslpath



我正在尝试编写一个脚本,当在Windows上的WSL中运行时,该脚本将通过wslpath工具传递拖放到bash窗口中的目录的位置。

# Drag and drop the directory into the Bash window
IFS="" read -r input
echo;
# If system is Windows Subsystem for Linux convert Windows paths to Unix paths
if [[ $(uname -r) =~ Microsoft$ ]]; then
input="$( wslpath "$input" )"
fi
# Use eval to parse spaces in the path as an array
eval "input=( $input )"
# List files and directories
ls -l "${input}"; echo;

如果目录名中有空格,则无法找到要列出的目录。

如果我将eval "input=( $input )"行移到Windows Subsystem for Linux条件的上方,如果目录名中有空格,它会找到目录,但如果没有空格,它不会找到。

如果我用下面的Bash-replace表达式替换行input="$( wslpath "$input" )",它可以使用空格或不使用空格,但驱动器号必须硬编码为input=${input/F:\//mnt/f/}

我读过很多关于Bash中引号求值顺序的线程,将参数作为数组传递给函数,然后扩展这些数组,但我真的很难做到这一点,我就是无法让它发挥作用。

由于只有一个路径,因此不需要数组。只要引用变量,路径中的空格就会得到正确处理。

实际上,将路径拆分为单词数组会导致信息丢失。您将不知道数组(a b)最初是a b(一个空格(还是a b(两个空格(。此外,您不需要eval来将变量拆分为单词。array=($var)是我们要走的路

这里的问题是Windows通过将路径用双引号括起来来粘贴带有空格的路径。也就是说,如果你拖动'n'dropC:a,你会得到字符串C:a,但如果拖动'n'dropC:a b,你会获得"C:a b"。bash不会解释这些引号,因为它们只是输入,而不是脚本的一部分。wslpath也不解释这些引号。相反,wslpath '"C:a b"'查找驻留在驱动器"C:上的名为a b"的文件。我们必须手动删除Windows"拖放"插入的引号。

IFS= read -r input; echo
if [[ "$(uname -r)" =~ Microsoft$ ]]; then
# is path quoted and contains a space?
if [[ "$input" =~ ^"(.* .*)"$ ]]; then
# remove quotes
input="${BASH_REMATCH[1]}"
fi
input="$( wslpath "$input" )"
fi
ls -l "${input}"; echo

最新更新