溫馨提示×

怎么用shell循環(huán)讀取目錄下的文件名

小億
316
2023-11-22 21:51:29
欄目: 編程語言

可以使用for循環(huán)來遍歷目錄下的文件名。

#!/bin/bash

# 遍歷當(dāng)前目錄下的文件名
for file in *
do
    echo $file
done

如果要遍歷指定目錄下的文件名,可以將目錄路徑作為參數(shù)傳遞給for循環(huán)。

#!/bin/bash

# 遍歷指定目錄下的文件名
for file in /path/to/directory/*
do
    echo $file
done

注意,在使用for循環(huán)遍歷文件名時(shí),如果文件名中包含空格或特殊字符,可能會導(dǎo)致處理錯(cuò)誤。為避免這種情況,可以使用雙引號將$file包圍起來。

#!/bin/bash

# 遍歷當(dāng)前目錄下的文件名,處理包含空格或特殊字符的文件名
for file in *
do
    echo "$file"
done

以上是使用for循環(huán)遍歷目錄下的文件名的簡單示例。根據(jù)需要,你可以在循環(huán)中添加其他操作。

0