如何執行 shell 找出指定的目錄下的檔案或是特別的檔案?
常用的語法如下:
for f in file1 file2 file3
do
echo "Processing $f" # always double quote "$f" filename
# do something on $f
done
您也可以透過變數
FILES="file1
/path/to/file2
/etc/resolve.conf
"
for f in $FILES
do
echo "Processing $f"
done
指定副檔名
for f in ./*.js
do
echo "Processing $f file...."
done
Sample Shell Script To Loop Through All Files
#!/bin/bash
# NOTE : Quote it else use array to avoid problems #
FILES="/path/to/*"
for f in $FILES
do
echo "Processing $f file..."
# take action on each file. $f store current file name
cat "$f"
done
檢查檔案是否存在
#!/bin/bash
FILES="/etc/sys*.conf"
for f in $FILES
do
# FAILSAFE #
# Check if "$f" FILE exists and is a regular file and then only copy it #
if [ -f "$f" ]
then
echo "Processing $f file..."
cp -f "$f" /dest/dir
else
echo "Warning: Some problem with \"$f\""
fi
done
副檔名
for f in /path/to/*.pdf
do
echo "Removing password for pdf file - $f"
# always "double quote" $f to avoid problems
/path/to/command --option "$f"
done
目前的目錄
dir="$PWD"
echo $dir
上一層的目錄
parent_dir="$(dirname "$dir")"
echo $parent_dir