我想做的是
我正在Windows上运行Git Bash,并且正在尝试为ls编写一个包装器函数,它可以正确地处理Windows的隐藏文件标志。
命令cmd.exe /c "dir /b /a/h"将输出目录中具有隐藏标志的文件列表。每个文件名都在一行中输出,由\r\n分隔(为Windows)。带空格的文件名用单引号括起来。
$ cmd.exe /c "/b /ah"
.gitconfig
desktop.ini
'hidden file.txt' 然后,我想将其格式化为最终ls调用的--ignore选项列表。
--ignore='.gitconfig' --ignore='desktop.ini' --ignore='hidden file.txt'我尝试过的
在设置了IFS='\r\n'之后,我使用了一个for循环,它应该允许我用--ignore='和'格式化每个文件名字符串。
function ls {
options=""
IFS="\r\n"
for filename in $(cmd.exe /c "dir /b /ah")
do options="${options}--ignore='$filename' "
done
echo $options
# command ls $options "$@"
}但是,字符串没有被拆分,并且输出中n和r的所有实例都被替换为一个空格,因此得到的字符串是乱码。
$ ls
--ig o e='.gitco fig
desktop.i i
hidde file.txt'我做错了什么?
发布于 2017-12-20 18:34:10
将选项收集到单个字符串变量中将是一个糟糕的结局。请改用数组。
ls () {
options=()
local IFS="\r\n"
while read -r filename; do
case $filename in \'*\')
filename=${filename#\'}; filename=${filename%\'};;
esac
options+=("--ignore=$filename")
done < <(cmd.exe /c "dir /b /ah")
# echo will flatten the arguments, maybe just run git here
echo "${options[@]}"
}另请参阅http://mywiki.wooledge.org/BashFAQ/050以获得更多讨论。
发布于 2017-12-20 18:27:43
您在options中echo文件名而不带引号,echo将它们作为单独的参数进行回显:
echo "$options"应该工作得很好。
发布于 2017-12-23 14:40:37
最后,我使用了@tripleee推荐的数组,但没有使用while read,而是使用了一个简单的for循环。不需要显式地处理多字文件名周围的引号。
function ls {
local IFS=$'\r\n'
options=()
for filename in $(cmd.exe /c "dir /b /ah 2> null")
do options+=("--hide=$filename")
done
command ls "${options[@]}" "$@"
}使用--hide选项而不是--ignore选项,以允许-a或--all按预期工作。
https://stackoverflow.com/questions/47903762
复制相似问题