|
|
茫茫網海中的冷日
發生過的事,不可能遺忘,只是想不起來而已! |
|
恭喜您是本站第 1729600
位訪客!
登入 | 註冊
|
|
|
|
發表者 |
討論內容 |
冷日 (冷日) |
發表時間:2016/8/16 2:19 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]Find Out If File Exists With Conditional Expressions
- Linux/UNIX: Find Out If File Exists With Conditional Expressions
by VIVEK GITE on FEBRUARY 16, 2006 last updated JANUARY 25, 2016
With the help of BASH shell and IF command, it is possible to find out if file exists or not on the filesystem. A conditional expressions (also know as “evaluating expressions”) can be used by [[ compound command and the test ([) builtin commands to test file attributes and perform string and arithmetic comparisons.
Syntax
The general syntax is: OR OR Where parameter can be any one of the following:
-e: Returns true value if file exists.
-f: Return true value if file exists and regular file.
-r: Return true value if file exists and is readable.
-w: Return true value if file exists and is writable.
-x: Return true value if file exists and is executable.
-d: Return true value if exists and is a directory.
Please note that the [[ works only in Bash, Zsh and the Korn shell, and is more powerful; [ and test are available in POSIX shells. Let us see some examples.
Find out if file /etc/passwd file exist or not
Type the following commands:
$ [ -f /etc/passwd ] && echo "File exist" || echo "File does not exist"
$ [ -f /tmp/fileonetwo ] && echo "File exist" || echo "File does not exist"
[[ example Type the following commands:
$ [[ -f /etc/passwd ]] && echo "File exist" || echo "File does not exist"
$ [[ -f /tmp/fileonetwo ]] && echo "File exist" || echo "File does not exist"
Find out if directory /var/logs exist or not Type the following commands:
$ [ -d /var/logs ] && echo "Directory exist" || echo "Directory does not exist"
$ [ -d /dumper/fack ] && echo "Directory exist" || echo "Directory does not exist"
[[ example
$ [[ -d /var/logs ]] && echo "Directory exist" || echo "Directory does not exist"
$ [[ -d /dumper/fake ]] && echo "Directory exist" || echo "Directory does not exist"
Are two files are the same?
Use the -ef primitive with the [[ new test command:
[[ /etc/resolv.conf -ef /etc/resolv.conf ]] && echo "Same files" || echo "Noop"
[[ /etc/resolv.conf -ef /etc/passwd ]] && echo "Same files" || echo "Noop"
Shell script example
You can use conditional expressions in a shell script:
#!/bin/bash
FILE="$1"
if [ -f "$FILE" ];
then
echo "File $FILE exist."
else
echo "File $FILE does not exist" >&2
fi
Save and execute the script:
$ chmod +x script.sh
$ ./script.sh /path/to/file
$ ./script.sh /etc/resolv.conf
You can use this technique to verify that backup directory or backup source directory exits or not in shell scripts. See example script for more information.
原文出處:Linux/UNIX: Find Out If File Exists With Conditional Expressions
|
|
|
冷日 (冷日) |
發表時間:2016/8/16 2:21 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]Bash Shell: Check File Exists or Not
- Bash Shell: Check File Exists or Not
by VIVEK GITE on APRIL 20, 2012 last updated APRIL 20, 2012
How do I test existence of a text file in bash running under Unix like operating systems?
You need to use the test command to check file types and compare values. The same command can be used to see if a file exist of not. The syntax is as follows:
test -e filename
[ -e filename ]
test -f filename
[ -f filename ]
The following command will tell if a text file called /etc/hosts exists or not using bash conditional execution :
[ -f /etc/hosts ] && echo "Found" || echo "Not found"
Sample outputs: The same code can be converted to use with if..else..fi which allows to make choice based on the success or failure of a test command:
#!/bin/bash
file="/etc/hosts"
if [ -f "$file" ]
then
echo "$file found."
else
echo "$file not found."
fi
File test operators The following operators returns true if file exists:
-b FILE
FILE exists and is block special
-c FILE
FILE exists and is character special
-d FILE
FILE exists and is a directory
-e FILE
FILE exists
-f FILE
FILE exists and is a regular file
-g FILE
FILE exists and is set-group-ID
-G FILE
FILE exists and is owned by the effective group ID
-h FILE
FILE exists and is a symbolic link (same as -L)
-k FILE
FILE exists and has its sticky bit set
-L FILE
FILE exists and is a symbolic link (same as -h)
-O FILE
FILE exists and is owned by the effective user ID
-p FILE
FILE exists and is a named pipe
-r FILE
FILE exists and read permission is granted
-s FILE
FILE exists and has a size greater than zero
-S FILE
FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE
FILE exists and its set-user-ID bit is set
-w FILE
FILE exists and write permission is granted
-x FILE
FILE exists and execute (or search) permission is granted
The syntax is same (see File operators (attributes) comparisons for more info):
if [ operator FileName ]
then
echo "FileName - Found, take some action here"
else
echo "FileName - Not found, take some action here"
fi
原文出處:Bash Shell: Check File Exists or Not
|
|
|
冷日 (冷日) |
發表時間:2016/8/16 2:26 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]Bash Shell Check Whether a Directory is Empty or Not
- Bash Shell Check Whether a Directory is Empty or Not
by VIVEK GITE on NOVEMBER 22, 2007 last updated MARCH 21, 2014
How do I check whether a directory is empty or not under Linux / UNIX using a shell script? I would like to take some action if directory is empty on a Linux or Unix like system. How can I check from bash/ksh shell script if a directory contains files? How do I check whether a directory is empty or not?
There are many ways to find out if a directory is empty or not under Linux and Unix bash shell. You can use the find command to list only files. In this example, find command will only print file name from /tmp. If there is no output, directory is empty.
Check whether a directory is empty or not using find command
The basic syntax is as follows:
find /dir/name -type -f -exec command {} \;
OR GNU/BSD find command syntax:
find /path/to/dir -maxdepth 0 -empty -exec echo {} is empty. \;
OR
find /path/to/dir -type d -empty -exec command1 arg1 {} \;
In this example, check whether a directory called /tmp/ is empty or not, type:
$ find "/tmp" -type f -exec echo Found file {} \;
Sample outputs:
Found file /tmp/_.c
Found file /tmp/orbit-vivek/bonobo-activation-server-ior
Found file /tmp/orbit-vivek/bonobo-activation-register.lock
Found file /tmp/_.vsl
Found file /tmp/.X0-lock
Found file /tmp/.wine-1000/server-802-35437d/lock
Found file /tmp/.wine-1000/cxoffice-wine.lock
Found file /tmp/ksocket-vivek/Arts_PlayObjectFactory
Found file /tmp/ksocket-vivek/Arts_SimpleSoundServer
Found file /tmp/ksocket-vivek/secret-cookie
Found file /tmp/ksocket-vivek/Arts_AudioManager
Found file /tmp/ksocket-vivek/Arts_SoundServer
Found file /tmp/ksocket-vivek/Arts_SoundServerV2
Found file /tmp/vcl.XXf8tgOA
Found file /tmp/Tracker-vivek.6126/cache.db
Found file /tmp/gconfd-vivek/lock/ior
However, the simplest and most effective way is to use ls command with -A option:
$ [ "$(ls -A /path/to/directory)" ] && echo "Not Empty" || echo "Empty"
or
$ [ "$(ls -A /tmp)" ] && echo "Not Empty" || echo "Empty"
You can use if..else.fi in a shell script:
#!/bin/bash
FILE=""
DIR="/tmp"
# init
# look for empty dir
if [ "$(ls -A $DIR)" ]; then
echo "Take action $DIR is not Empty"
else
echo "$DIR is Empty"
fi
# rest of the logic
Here is another example using bash for loop to check for any *.c files in the ~/projects/ directory:
# Bourne/bash for loop example
for z in ~/projects/*.c; do
test -f "$z" || continue
echo "Working on $z C program..."
done
Check if folder /data/ is empty or not using bash only features From the Linux and Unix bash(1) man page:
nullglob If set, bash allows patterns which match no files to expand to a null string, rather than themselves.
dotglob – If set, bash includes filenames beginning with a . in the results of pathname expansion.
#!/bin/bash
# Set the variable for bash behavior
shopt -s nullglob
shopt -s dotglob
# Die if dir name provided on command line
[[ $# -eq 0 ]] && { echo "Usage: $0 dir-name"; exit 1; }
# Check for empty files using arrays
chk_files=(${1}/*)
(( ${#chk_files[*]} )) && echo "Files found in $1 directory." || echo "Directory $1 is empty."
# Unset the variable for bash behavior
shopt -u nullglob
shopt -u dotglob
Sample outputs:
$ ./script.sh /tmp
Files found in /tmp directory.
$ mkdir /tmp/foo
$ ./script.sh /tmp/foo
Directory /tmp/foo/ is empty.
A note about ksh user Try for loop as follows:
## In ksh93, prefix ~(N) in front of the pattern
## For example, find out if *.mp4 file exits or not in a dir
cd $HOME/Downloads/music/
for f in ~(N)*.mp4; do
# do something if file found
echo "Working on $f..."
done
原文出處:Bash Shell Check Whether a Directory is Empty or Not*/
|
|
冷日 (冷日) |
發表時間:2016/8/16 2:32 |
- Webmaster

- 註冊日: 2008/2/19
- 來自:
- 發表數: 15771
|
- [轉貼]Bash scripting: test for empty directory
- Bash scripting: test for empty directory
I want to test if a directory doesn't contain any files. If so, I will skip some processing.
I tried the following:
if [ ./* == "./*" ]; then
echo "No new file"
exit 1
fi
That gives the following error:
line 1: [: too many arguments
Is there a solution/alternative?
if [ "$(ls -A /path/to/dir)" ]; then
echo "Not Empty"
else
echo "Empty"
fi
Also, it would be cool to check if the directory exists before.
if [ $(find $DIR_TO_CHECK -maxdepth 0 -type d -empty 2>/dev/null) ]; then
echo "Empty directory"
else
echo "Not empty or NOT a directory"
fi
No need for counting anything or shell globs. You can also use read in combination with find. If find's output is empty, you'll return false:
if find /some/dir -mindepth 1 | read; then
echo "dir not empty"
else
echo "dir empty"
fi
This should be portable.
This will do the job in the current working directory (.):
[ `ls -1A . | wc -l` -eq 0 ] && echo "Current dir is empty." || echo "Current dir has files (or hidden files) in it."
or the same command split on three lines just to be more readable:
[ `ls -1A . | wc -l` -eq 0 ] && \
echo "Current dir is empty." || \
echo "Current dir has files (or hidden files) in it."
Just replace ls -1A . | wc -l with ls -1A | wc -l if you need to run it on a different target folder. Edit: I replaced -1a with -1A (see @Daniel comment)
#!/bin/bash
if [ -d /path/to/dir ]; then
# the directory exists
[ "$(ls -A /path/to/dir)" ] && echo "Not Empty" || echo "Empty"
else
# You could check here if /path/to/dir is a file with [ -f /path/to/dir]
fi
Use the following:
count="$( find /path -mindepth 1 -maxdepth 1 | wc -l )"
if [ $count -eq 0 ] ; then
echo "No new file"
exit 1
fi
This way, you're independent of the output format of ls. -mindepth skips the directory itself, -maxdepth prevents recursively defending into subdirectories to speed things up.
This is all great stuff - just made it into a script so I can check for empty directories below the current one. The below should be put into a file called 'findempty', placed in the path somewhere so bash can find it and then chmod 755 to run. Can easily be amended to your specific needs I guess.
#!/bin/bash
if [ "$#" == "0" ]; then
find . -maxdepth 1 -type d -exec findempty "{}" \;
exit
fi
COUNT=`ls -1A "$*" | wc -l`
if [ "$COUNT" == "0" ]; then
echo "$* : $COUNT"
fi
I think the best solution is:
files=$(shopt -s nullglob; shopt -s dotglob; echo /MYPATH/*)
[[ "$files" ]] || echo "dir empty"
thanks to http://stackoverflow.com/a/91558/520567 This is an anonymous edit of my answer that might or might not be helpful to somebody: A slight alteration gives the number of files:
files=$(shopt -s nullglob dotglob; s=(MYPATH/*); echo ${s[*]})
echo "MYPATH contains $files files"
This will work correctly even if filenames contains spaces.
Using an array:
files=( * .* )
if (( ${#files[@]} == 2 )); then
# contents of files array is (. ..)
echo dir is empty
fi
A hacky, but bash-only, PID-free way:
is_empty() {
test -e "$1/"* 2>/dev/null
case $? in;
1) return 0 ;;
*) return 1 ;;
esac
}
This takes advantage of the fact that test builtin exits with 2 if given more than one argument after -e: First, "$1"/* glob is expanded by bash. This results in one argument per file. So
if there are no files, test -e "" is run, which obviously always fails, i.e. returns 1 for "no". If there is one file, test -e "dir/file" is run, which returns 0. But if there are more files than 1, bash reports it as usage error, i.e. 2. case wraps the whole logic around so that only the first case, with 1 exit status is reported as success.
Possible problems I haven't checked:
There are more files than number of allowed arguments--I guess this could behave similar to case with 2+ files. Or there is actually file with an empty name--I'm not sure it's possible on any sane OS/FS.
原文出處:Bash scripting: test for empty directory - Super User*/
|
|
|