Bash 常规文件的测试意外失败
我想写下一个bash脚本,它接受一个路径名、一个新目录名和一些字符串,并且只将该路径中的文件及其子文件夹复制到新创建的目录中,这些文件是常规文件,并且至少包含一个字符串 为了测试我的脚本,我创建了一些虚拟目录Bash 常规文件的测试意外失败,bash,Bash,我想写下一个bash脚本,它接受一个路径名、一个新目录名和一些字符串,并且只将该路径中的文件及其子文件夹复制到新创建的目录中,这些文件是常规文件,并且至少包含一个字符串 为了测试我的脚本,我创建了一些虚拟目录 /home/haunted85/Documenti/Sandbox/: total 20 drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16:42 . drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16
/home/haunted85/Documenti/Sandbox/:
total 20
drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16:42 .
drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16:40 ..
drwxr-xr-x 2 haunted85 haunted85 4096 apr 13 16:42 A
-rw-r--r-- 1 haunted85 haunted85 236 apr 13 16:42 a.out
drwxr-xr-x 2 haunted85 haunted85 4096 apr 13 16:43 B
/home/haunted85/Documenti/Sandbox/A:
total 16
drwxr-xr-x 2 haunted85 haunted85 4096 apr 13 16:42 .
drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16:42 ..
-rw-r--r-- 1 haunted85 haunted85 93 apr 13 16:41 a.out
-rw-r--r-- 1 haunted85 haunted85 101 apr 13 16:42 b.out
/home/haunted85/Documenti/Sandbox/B:
total 12
drwxr-xr-x 2 haunted85 haunted85 4096 apr 13 16:43 .
drwxr-xr-x 4 haunted85 haunted85 4096 apr 13 16:42 ..
-rw-r--r-- 1 haunted85 haunted85 292 apr 13 16:43 c.out
这是我的剧本
#! /bin/sh
if [ "$#" -lt "3" ]; then
echo "Error: cannot perform any task without enough input." 2>&1
echo "Usage: ./creaDirectory <path_name> <dir_name> <word>[, <word2>, ..., <wordN>]"
exit 1
else
if [ -d "$1" ]; then
# Saving pathname...
path_name=$1
# Moving forward
shift
# Saving new dir name...
dir_name=$1
# Moving forward
shift
# Creating new directory
mkdir $dir_name
# If correctly created...
if [ "$?" -eq "0" ]; then
echo "$dir_name created."
# For every file in the current directory and its subfolders...
for file in `ls -R $path_name`
do
echo "Checking $file..."
# if the file is regular
if [ -f $file ]; then
echo "$file is regular"
# perform other actions as well...
else
echo "$file is not regular"
fi
done
else
echo "Error: cannot create new directory." 2>&1
exit 3
fi
else
echo "$1 does not exist or it is not a directory." 2>&1
exit 2
fi
fi
请注意,
ls-R$path
将返回没有路径的文件名,例如,如果
for file in `ls -R $path_name`
do
echo $file
done
您的输出将类似于
/home/haunted85/Documenti/Sandbox/:
A
a.out
B
etc...
你会做什么
if [ -f A ]
这将失败,因为A
不在执行脚本的目录中
试一试
相反,它将返回所有匹配文件的完整路径。文件名/路径中是否有空格?也许
[-f“$file”]
会有帮助。@MarcB否,没有空格。如果在告诉您是否为常规文件的同时添加额外的回显以显示$file
的值,该值是否符合预期?ie文件名是否正确?@JoshJolly是的,它们是现有的正确路径/文件名。执行脚本时,您当前的目录是什么?当您键入ls dirname
时,会得到一个没有dirname的文件名列表。您应该使用find
而不是ls
您不应该对$(ls…)中的文件使用或对$(find…)中的文件使用,除非
if [ -f A ]
for file in `find $path_name -type f`