Simple ZSH function and files with spaces in their name

血红的双手。 提交于 2019-12-14 03:59:00

问题


I have put the following function into my ~/.zshrc file:

function note() {
    vim $HOME/Dropbox/$1.md
}

When I call it with note "20150209-132501-Recx-new note today.md" for example it creates a new file but with the file name "20150209-132501-Recx-new". I realise this is a simple question but how do I get it to create the note with the full name?


回答1:


The shell performs parameter substitution and word-splitting in this order. This means you eventually execute

vim /home/username/Dropbox/20150209-132501-Recx-new note today.md.md

I.e. you call vim with three file names. If you want to suppress word-splitting on the substituted part, you must use quotes in the function definition as well:

function note() {
    vim "$HOME/Dropbox/$1.md"
}

and call it with

note "20150209-132501-Recx-new note today"

EDIT 1: This version of note concatenates all args with a single space:

function note() {
    filename=$1
    while test $# -gt 1; do shift; filename="$filename $1"; done
    vim "$HOME/Dropbox/$filename.md"
}

EDIT 2: This might be even easier:

function note() {
    vim "$HOME/Dropbox/$*.md"
}


来源:https://stackoverflow.com/questions/28410891/simple-zsh-function-and-files-with-spaces-in-their-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!