我可以在 Windows 上的 Ubuntu 或适用于 Linux 的 Windows 子系统 (WSL) 上使用 Bash 将文件拖放到 .sh 脚本中吗?

Ale*_*Sim 6 linux script bash windows-10 windows-subsystem-for-linux

我想通过简单地将多个文件拖到脚本文件上来将多个文件作为 Windows 10 中 .sh 脚本的参数传递;这可能吗?

Ale*_*Sim 2

Windows 10(v1607 及更高版本)默认情况下仍然不提供此功能。

幸运的是,您可以使用注册表项启用它(下面提供)

当然,该键确实可以将 .sh 脚本与 bash.exe 关联起来,因此也可以简单地双击该脚本

https://www.codeproject.com/Articles/1214365/Proper-Bash-scripting-on-Windows-Associate-SH-scri (更新:为 Ubuntu、OpenSUSE 和旧版安装添加了新的图标选项)

该键还启用在用户模式和提升模式下运行脚本的选项(前者通过双击,后者是右键单击选项),而额外的(可选)键则启用右键单击>使用 nano 编辑

请记住,您首先必须安装Windows Subsystem for Linux并将其设置为打开 .sh 文件的默认程序(该程序的路径是 C:/Windows/System32/bash.exe)

主注册表项执行以下脚本

#This makes bash.exe silently execute the command below (whole code)
"%SYSTEMROOT%\System32\bash.exe" -c

#Gets all file paths without expansion/substitution
read -r -d '' path_param <<'EOF'
%*
EOF
read -r -d '' path_exec <<'EOF'
%L
EOF

#Parses all dragged files' paths from Windows paths to unix paths
path_param=$(echo $path_param | tr -d '"' | sed 's/[[:space:]]\([A-Z]:\)/\n\1/g' | sed 's/[A-Z]:/\/mnt\/\L&/g' | tr '\\' '\/'\');
mapfile -t path_param <<< "$path_param";
path_param=("${path_param[@]//:}");

#Same, but with the .sh script path
path_exec=$(echo $path_exec | sed 's/[[:space:]]\([A-Z]:\)/\n\1/g' | sed 's/[A-Z]:/\/mnt\/\L&/g' | tr '\\' '\/'\'); 
path_exec="${path_exec//:}";

#Sets working directory to the folder where the script is located
cd "${path_exec%\/*}";

#Executes script with or without parameters
if [[ ${path_param[@]} == "" ]];
    then "$path_exec";
    else "$path_exec" "${path_param[@]/#${path_exec%\/*}\/}";
fi;

#Leaves WSL console open after the .sh script finishes executing
cd ~; bash;
Run Code Online (Sandbox Code Playgroud)