How to test for if two files exist?

前端 未结 4 1970
耶瑟儿~
耶瑟儿~ 2021-02-02 07:11

I would like to check if both files exist, but I am getting

test.sh: line 3: [: missing `]\'

Can anyone see what\'s wrong?

#!/b         


        
相关标签:
4条回答
  • 2021-02-02 07:23
    if [ -e .ssh/id_rsa -a -e .ssh/id_rsa.pub ]; then
     echo "both exist"
    else
     echo "one or more is missing"
    fi
    

    Here,

    -e check only the file is exits or not.If exits,it return true.else,it return false.

    -f also do the same thing but,it check whether the given file is regular file or not.based on that it return the true/false.

    Then you are using &&.So that,It need two [[ .. ]] brackets to execute.

    instead you can use the -a [same as && operator] -o [same as || operator]. If you need more information go through this link

    http://linux.die.net/man/1/bash.

    0 讨论(0)
  • 2021-02-02 07:25

    [[ is bash-specific syntax. For POSIX-compatible shells, you need:

    [ -f file1 ] && [ -f file2 ]
    
    0 讨论(0)
  • 2021-02-02 07:34
    [ -f .ssh/id_rsa -a -f .ssh/id_rsa.pub ] && echo both || echo not
    

    or

    [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]] && echo both || echo not
    

    also, if you for the [[ ]] solution, you'll probably want to change #!/bin/sh to #!/bin/bash in compliance with your question's tag.

    0 讨论(0)
  • 2021-02-02 07:46

    Try adding an additional square bracket.

    if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then
    
    0 讨论(0)
提交回复
热议问题