![bash shell 循環遍歷目錄列出內容和可執行性](https://rvso.com/image/83671/bash%20shell%20%E5%BE%AA%E7%92%B0%E9%81%8D%E6%AD%B7%E7%9B%AE%E9%8C%84%E5%88%97%E5%87%BA%E5%85%A7%E5%AE%B9%E5%92%8C%E5%8F%AF%E5%9F%B7%E8%A1%8C%E6%80%A7.png)
我目前正在做作業,我需要取得給定的目錄路徑,並從中列出其中的檔案和目錄。同時也包括它是否可執行。我還受到限制,不允許使用 bash 以外的任何其他語言。
我最初的想法是使用ll
並cut
獲得我需要的東西,但我似乎無法讓它發揮作用。然後我想我可以使用類似的東西(不起作用,只是一個想法)
read input
for f in $input
do
if [[ -x "$f" ]]
then
echo "$f is executable"
else
echo "$f is not executable"
fi
done
我需要類似的輸出,但我不知道如何到達那裡
檔案名稱1是可執行文件
檔案名稱2不可執行
目錄1是可執行文件
答案1
試試像
my=($(ls -la $dr |awk {'print $9'}))
echo ${my[@]}
for i in "${my[@]}"
do
if [[ -x "$i" ]]
then
echo "File '$i' is executable"
else
echo "File '$i' is not executable or found"
fi
done
答案2
您正在取得一個目錄,然後檢查該目錄本身是否可執行,而不是按照您想要的方式查看其內容。
read input
for f in ${input}/*; do
echo -n "$f is "
type=""
if [[ -x "$f" ]]; then
type="executable"
else
type="non-executable"
fi
if [[ -d "$f" ]]; then
type="$type directory"
fi
echo "$type"
done
確保 的值$input
是一個可讀目錄是我留給您的練習。