Reputation: 383
How do i create a script to check for the file is hidden or not?
#!/bin/bash
FILE="$1"
if [ -f "$FILE" ];
then
echo "File $FILE is not hidden."
else
echo "File $FILE is hidden" >&2
fi
but it is unable to do so. Please help me.
Upvotes: 1
Views: 1016
Reputation: 5251
The test command would be:
[[ "${file##*/}" == .* ]]
It's necessary to remove the path, to see if file name starts with .
. Here I used prefix removal. It's the most efficient, but will choke if a file contains slashes (very unlikely, but be aware).
A full script should include a test that the given file actually exists:
#!/bin/bash
file=$1
[[ -e "$file" ]] && { echo "File does not exist: $file" >&2; exit 1; }
if [[ "${file##*/}" == .* ]]; then
echo "Hidden: $file"
else
echo "Not hidden: $file"
fi
You could also list all hidden files in a directory:
find "$dir" -name .\*
Or all not hidden files:
find "$dir" -name '[^.]*'
Depending on the task, it's probably better to use a list of hidden or not hidden files, to work on.
Also, by default, ls
does not list hidden files. Unless you use -a
.
Upvotes: 0
Reputation: 14688
You essentially have to check if filename starts with . (period).
filename=$(basename -- "$FILE")
Then you have to use pattern matching
if [[ $filename == .* ]]
then
# do something
fi
Upvotes: 0
Reputation: 782166
Check if the filename begins with .
:
file=$1
base=$(basename "$file")
if [[ $base == .* ]]
then echo "File $file is hidden"
else echo "File $file is not hidden"
fi
Upvotes: 1