如何在 CLI (bash/zsh) 中"命令文件.txt或another_file.txt"



是否可以运行file.txt作为参数的命令,或者如果file.txt不存在,则使用another_file.txt运行命令?

为了使我的请求更加现实,我想默认使用工作区文件运行VSCode,或者,如果工作区文件不存在,则使用.(当前文件夹(运行VSCode,如下所示:

code *.code-workspace OR .

如果*.code-workspace存在,则命令应等效于code *.code-workspace,否则推荐应等效于code .

bashzsh中可能吗?(我正在使用zsh+oh-my-zsh(

在 bash 中,如果没有匹配项,您可以使用nullglob将通配符(如*(扩展为无。然后将所有内容放入数组中并检索第一个条目。请注意,$array与第一个数组条目${array[0]}相同。

#! /bin/bash
shopt -s nullglob
files=(*.code-workspace .)
code "$files"

如果有一个以.code-workspace结尾的文件,上面的代码code firstMatchOf.code-workspace开始,如果没有这样的文件,则.

对于zsh,您可以通过将shopt -s nullglob替换为setopt null_glob来执行相同的操作。

请注意,上述方法仅适用于通配符。 即使a不存在,files=(a b); code "$files"也会调用code a。在这里,您可以改用以下函数,该函数应该在每种情况下都有效:

#! /bin/sh
firstExisting() {
set -- "$@" . # ensure termination 
while ! [ -e "$1" ]; do
shift
done
printf %s\n "$1"
}

使用示例:

code "$(firstExisting *.code-workspace .)"

或者只是

code "$(firstExisting *.code-workspace)"

。因为.是默认值,以防没有任何参数存在。 这里不需要shopt -s nullglob

最新更新