[英]Shell Scripting: Print directory names and files with specifics
In my script, I am asking the user to input a directory and then list all the files in that specific directory. 在我的脚本中,我要求用户输入一个目录,然后列出该特定目录中的所有文件。 What I want to do with that is to make the display a little better in which I would be able to display a "/" if the item in the directory is another directory and if it is an executable file (not an executable directory), print with a **". 我想要做的就是使显示更好一点,如果目录中的项目是另一个目录,并且它是一个可执行文件(不是可执行目录),我将能够显示“/”,打印**“。
This is what I have: 这就是我所拥有的:
echo “Directory: “
read thing
for var123 in $thing*
do
echo $var123
done
In a directory I have a few folders and a few scripts that have the execute permission. 在一个目录中,我有一些文件夹和一些具有执行权限的脚本。 when I run the script I want to say 当我运行脚本时我想说
/folder1/subfolder1/ /文件夹1 / subfolder1 /
/folder1/subfolder2/ /文件夹1 / subfolder2 /
/folder1/file1* /资料夹/文件1 *
/folder1/file2* /资料夹/文件2 *
I am new to this and have no clue what I am doing. 我是新手,不知道我在做什么。 Any help will be greatly appreciated. 任何帮助将不胜感激。
ls -F
is your friend here - if you want to do it for the current directory: ls -F
是你的朋友 - 如果你想为当前目录做这件事:
ls -F
If you want to do it for all files & subfolders of the current directory: 如果要对当前目录的所有文件和子文件夹执行此操作:
find * -exec ls -Fd {} \;
... and for a given directory: ......并且对于给定目录:
echo "Directory: "
read DIR
find $DIR/* -exec ls -Fd {} \;
Edit: ls -F
will append a /
to directories and a *
to executables. 编辑: ls -F
将附加一个/
到目录和一个*
到可执行文件。 If you want **
instead, just use sed to replace them: 如果您想要**
,只需使用sed替换它们:
find $DIR/* -exec ls -Fd {} \; | sed 's/\*$/&&/'
And this approach works in all shells, not just bash. 这种方法适用于所有 shell,而不仅仅是bash。
You might want to check and make sure the user inputs something that ends in a /
first. 您可能需要检查并确保用户输入以/
first结尾的内容。
eg 例如
[[ $thing =~ '/'$ ]] || thing="$thing/"
Also check if it exists 还要检查它是否存在
eg 例如
[[ -d $thing ]] || exit 1
Then for checking if it's a directory use the -d
test as above. 然后检查它是否是目录使用上面的-d
test。 To check if executable file use -x
. 检查可执行文件是否使用-x
。 So putting that all together, try: 所以把它们放在一起,试试:
#!/bin/bash
echo “Directory: “
read thing
[[ $thing =~ '/'$ ]] || thing="$thing/"
[[ -d $thing ]] || exit 1
for var123 in "$thing"*
do
if [[ -f $var123 && -x $var123 ]]; then
echo "$var123**"
elif [[ -d $var123 ]]; then
echo "$var123/"
else
echo "$var123"
fi
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.