bus*_*ter 1 bash shell scripting loops for-loop
我正在尝试编写一个显示文件内容的简单bash脚本.
#!/bin/bash
echo 'Input the path of a file or directory...'
read File
if [ -e $File ] && [ -f $File ] && [ -r $File ]
then
echo 'Displaying the contents of the file '$File
cat $File
elif [ -d $File ] && [ -r $File ]
then
echo 'Displaying the contents of the directory '$File
for FILE in `ls -R $File`
do
cd $File/$FILE
echo 'Displaying the contents of the file '$FILE
cat $FILE
done
else
echo 'Oops... Cannot read file or directory !'
fi
Run Code Online (Sandbox Code Playgroud)
用户应输入文件或目录路径.如果用户输入文件,程序将使用cat显示该文件.如果用户输入目录,则应显示所有文件的内容,包括子目录中的文件.该程序的那部分不能很好地工作.我想得到一个结果,不会显示错误,如'没有这样的文件或目录',但只显示文件的内容.你能帮助我吗 ?提前致谢.
ls -R是查找所有子目录中所有文件的错误工具. find是一个更好的选择:
echo "displaying all files under $File"
find "$File" -type f -printf "Displaying contents of %p\n" -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)