I would like to check if both files exist, but I am getting
test.sh: line 3: [: missing `]'
Can anyone see what's wrong?
#!/bin/sh if [ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]; then echo "both exist" else echo "one or more is missing" fi
Probably the easiest way to compare two files is to use the diff command. The output will show you the differences between the two files. The < and > signs indicate whether the extra lines are in the first (<) or second (>) file provided as arguments.
When checking if a file exists, the most commonly used FILE operators are -e and -f . The first one will check whether a file exists regardless of the type, while the second one will return true only if the FILE is a regular file (not a directory or a device).
You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
Use comm -12 file1 file2 to get common lines in both files. You may also needs your file to be sorted to comm to work as expected. Or using grep command you need to add -x option to match the whole line as a matching pattern. The F option is telling grep that match pattern as a string not a regex match.
Try adding an additional square bracket.
if [[ -f .ssh/id_rsa && -f .ssh/id_rsa.pub ]]; then
[ -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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With