check if argv is a directory

396 views Asked by At

I'm using FISH (Friendly Interactive SHell)

and I created 2 functions :

function send
    command cat $argv | nc -l 55555
end

--> send a file via nc

function senddir
    command tar cjf copy.tar $argv; cat copy.tar | nc -l 55555; rm copy.tar
end

--> send a dir by compressing it via nc

Now, I wan't to refactor and create a send function that does both, for this I need to check if argv is a dir. How can I do it with fish?

3

There are 3 answers

0
chepner On BEST ANSWER

Same as in other shells, although in fish you are actually using an external program, not a shell built-in.

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

Actually, you don't need the temp file and can pipe the output of tar directly to nc -l, which allows you to simplify the function to

function send
    if test -d $argv
        command tar cj $argv
    else
        command cat $argv
    end | nc -l 55555
end
0
Charlon On
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
1
glenn jackman On

Note that $argv is an array, so if you pass more than one argument, test will barf.

$ test -d foo bar
test: unexpected argument at index 2: 'bar'

Coding a little more defensively:

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