我想写下一个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: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
我的问题是条件if [ -f $file ];
似乎没有正常工作,因为没有找到常规文件,但显然不是这样!那么我做错了什么?
编辑:添加我得到的输出。您可以自己查看,这些都是正确的路径/文件名:
copia_file created.
Checking /home/haunted85/Documenti/Sandbox/:...
/home/haunted85/Documenti/Sandbox/: is not a regular file
Checking A...
A is not a regular file
Checking a.out...
a.out is not a regular file
Checking B...
B is not a regular file
Checking /home/haunted85/Documenti/Sandbox/A:...
/home/haunted85/Documenti/Sandbox/A: is not a regular file
Checking a.out...
a.out is not a regular file
Checking b.out...
b.out is not a regular file
Checking /home/haunted85/Documenti/Sandbox/B:...
/home/haunted85/Documenti/Sandbox/B: is not a regular file
Checking c.out...
c.out is not a regular file
答案 0 :(得分:0)
请注意,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
不在脚本执行的目录中。
尝试
for file in `find $path_name -type f`
相反,它将返回所有匹配文件的完整路径。