我需要一些帮助才能让这个运行起来。只有两个部分。
我是bash脚本的新手。如何输入单个文件名,我该怎么重复? PS到目前为止我似乎没有尝试使用while循环。
ifSpaces(){
#if more than one file name if statement(checks for spaces)
if [ "$#" -eq "$(echo "$@" | wc -w)" ]
then
echo -n "Please enter a filename: ";
read filename
else
echo -n "Please enter a single filename! ";
fi
}
该函数应该测试文件是否可以写入。它似乎通过它而不是正确测试它。但我不太确定。基本上,它有什么问题,请进行更正,因为当人们告诉我并且没有告诉我如何时,我没有得到它。
#how do I get this to work?
testFiles(){
#loop through files and test each one
for filename in "$@"
do
filename="$@"
# put this in a loop that grabs all the values.
# test all the file names
while [ -f "$filename" ]
do
if [ -w $filename ]
then
echo "The file exists and is writable";
overWriteFile
saveResults
elif [ -d $filename ]
then
read filename
echo "$filename";
echo "The file you specified exists and is a directory".
saveResults
else
>$directory$filename;
fi
done
echo "$filename";
echo "The file you specified exists and is neither a regular file nor a directory.";
done
saveResults
}
答案 0 :(得分:3)
ifSpaces()
函数需要更好的定义 - 它该做什么?
如何测试字符串中的空格(又名文件名)?
spacesInName()
{
case "$1" in
(* *) return 0;;
(*) return 1;;
esac
}
因此:
ifSpaces()
{
filename=$1
while spacesInName "$filename"
do
echo -n "Enter a filename without spaces: "
read filename
done
return $filename
}
好的 - 完成了,现在我们问“为什么?”。确保您的代码使用任何有效的文件名不是更好,因为所有主要操作系统(文件系统)都识别其中带有空格的文件名是否有效?
此外,提示的shell脚本通常是不文明的;当没有用户提供输入时,它们当然不能可靠地使用,并且它们不能在命令的管道中可靠地使用。这严重限制了它们的用处。
因此,通用脚本不会提问。专用脚本可以提问。它确实取决于脚本的设计目标和使用者。但是尽可能避免骚扰。
你的第二个功能同样非常困惑。目前还不是很清楚它应该做什么,但这看起来比原来更合理:
testFiles()
{
for filename in "$@"
do
if [ -w "$filename" ]
then
echo "The file $filename exists and is writable";
saveResults "$filename"
elif [ -d "$filename" ]
then
echo "The file $filename exists and is a directory".
elif [ -f "$filename" ]
then
echo "The file $filename exists but is not writable"
else
echo "Either $filename does not exist or it is neither"
echo "a file nor a directory"
fi
done
}
修改为每个丢失文件提示一次以获得答案 - 创建文件...
testFiles()
{
for filename in "$@"
do
if [ -w "$filename" ]
then
echo "The file $filename exists and is writable";
saveResults "$filename"
elif [ -d "$filename" ]
then
echo "The file $filename exists and is a directory".
elif [ -f "$filename" ]
then
echo "The file $filename exists but is not writable"
elif [ ! -e "$filename ]
then
echo "$filename does not exist - create it? "
read yesno
case "$yesno" in
([Yy]*) cp /dev/null "$filename"
saveResults "$filename"
;;
(*) echo "OK - ignoring $filename"
;;
esac
fi
done
}