是否可以运行file.txt
作为参数的命令,或者如果file.txt
不存在,则使用another_file.txt
运行命令?
为了使我的请求更加现实,我想默认使用工作区文件运行VSCode,或者,如果工作区文件不存在,则使用.
(当前文件夹(运行VSCode,如下所示:
code *.code-workspace OR .
如果*.code-workspace
存在,则命令应等效于code *.code-workspace
,否则推荐应等效于code .
在bash
或zsh
中可能吗?(我正在使用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
。