【问题标题】:check if argv is a directory检查 argv 是否为目录
【发布时间】:2015-01-09 15:26:18
【问题描述】:
我正在使用 FISH(友好的交互式 SHell)
我创建了 2 个函数:
function send
command cat $argv | nc -l 55555
end
--> 通过 nc 发送文件
function senddir
command tar cjf copy.tar $argv; cat copy.tar | nc -l 55555; rm copy.tar
end
--> 通过 nc 压缩发送一个目录
现在,我不想重构并创建一个两者都执行的发送函数,为此我需要检查 argv 是否是一个目录。我怎么能用鱼做呢?
【问题讨论】:
标签:
function
shell
directory
fish
【解决方案1】:
与其他 shell 相同,尽管在 fish 中您实际上使用的是外部程序,而不是内置的 shell。
function send
if test -d $argv
command tar cjf copy.tar $argv; cat copy.tar | nc -l 55555; rm copy.tar
else
command cat $argv | nc -l 55555
end
end
其实你不需要临时文件,可以直接将tar的输出通过管道传递给nc -l,这样可以简化函数到
function send
if test -d $argv
command tar cj $argv
else
command cat $argv
end | nc -l 55555
end
【解决方案2】:
function send
if test -d $argv
command tar cjf $argv | nc -l 55555;
else if test -e $argv
command cat $argv | nc -l 55555;
else
echo "error: file/directory doesn't exist"
end
end
【解决方案3】:
注意$argv 是一个数组,所以如果你传递了多个参数,test 会出错。
$ test -d foo bar
test: unexpected argument at index 2: 'bar'
更具防御性的编码:
function send
if test (count $argv) -ne 1
echo "Usage: send file_or_dir"
return
else if test -d $argv[1]
# ...
else if test -f $argv[1]
# ...
else
# ...
end
end