How to see if the directory exists?
You can use the following to check for the existence of a directory:
if [[ -d "$1" ]]; then
If you want to check for any file you would use
if [[ -e "$1" || -L "$1" ]]; then
If you want to check if a file is a regular file (or symlink to regular file), but NOT a directory (or a device, socket, named pipe...) file then you can use:
if [[ -f "$1" ]]; then
If the file might exist but you want to be sure it is not zero size:
if [[ -s "$1" ]] then;
All those tests are based on the result of the stat()
system call (except for -L
that relies on lstat()
). If you don't have the permission to do such a call on the file (for example because you don't have search access to the directory the file is in or to directories involved in the resolution of the file for symlinks), then those tests will silently return false as if the files didn't exist.
[[ ... ]]
is a ksh
operator, also supported by bash
and zsh
. The standard equivalent (to use in sh
) is with the [
command (for the second example above, use [ -e "$1" ] || [ -L "$1" ]
).
Related videos on Youtube
user3334375
Updated on September 18, 2022Comments
-
user3334375 over 1 year
How can I check if
/bin/x86_64/bin/ls
is a directory in a bash shell scriptHere is what I tried:
#!/bin/bash if [ $# -eq 2 ]; then if [[ "$1" = /* ]] then cd ./bin/x86_64/bin/ls if [ -d "$1" ]; then echo "ok" i="$1" echo $i else echo "error2" exit fi else echo "error" exit fi fi
-
Skaperen almost 9 yearsdid you mean
if [[ "$1" = "/*" ]]
? -
Michael Durrant almost 9 yearsthe
cd ./bin/x86_65/bin/ls
seems unusual. Try a format more likecd "/bin/x86_64/bin"
using quotes and omitting the ls at the end as that is probably a command not a directory. -
Michael Durrant almost 9 yearsAlso, do you get an error ?
-
-
user3334375 almost 9 yearsdoesn;t work :(
-
Michael Durrant almost 9 yearsIn what way and AGAIN what error(s) do you get? It's good that you provide the details of what you have attempted, however you are unlikely to get much help unless you respond to the requests for more details about what error or response you get.
-
ryanpcmcquen over 8 yearsIf you use single brackets these commands will have more compatibility.