我正在编写一个 shell 脚本,想要删除文件夹中除一个文件之外的所有内容。
这段代码正是我想要的:
rm -r -v subfolder/!("file")
首先,从shell脚本中,我不能直接使用(),通过搜索我发现我应该将其更改为:/(file/)
因此我在脚本中写道:
rm -r -v subfolder/!/("file"/)
但是,当我运行脚本时,它一直出现以下错误:
rm: cannot remove 'subfolder/!(file)': No such file or directory
我从执行第一个 bash 命令时的同一文件夹运行脚本(“子文件夹”是 bash 当前位置中的现有文件夹,并且脚本也放在相同的当前位置)。
文件“Allclean”的完整脚本名称为:
#!/bin/sh
cd ${0%/*} || exit 1 # Run from this directory
# Source tutorial clean functions
. $WM_PROJECT_DIR/bin/tools/CleanFunctions
shopt -s extglob
echo "\n
Cleaning case (Transilient Scalar Transport Equation)
------------------------------------------------------------------------------------------------------------------------
"
echo " - Deleting 0 folder"
rm -f -r 0
echo " - Removing constant folder content except transportProperties"
cd constant
rm -r -v constant/!("transportProperties")
当我rm -r -v constant/!("transportProperties")
从 bash 运行时,它工作正常。运行时./Allclean
出现以下错误:
./Allclean: 6: ./Allclean: shopt: not found
Cleaning case (Transilient Scalar Transport Equation)
------------------------------------------------------------------------------------------------------------------------
- Deleting 0 folder
- Removing constant folder content except transportProperties
./Allclean: 16: ./Allclean: Syntax error: "(" unexpected
答案1
使用带有删除选项的查找功能
yiheng@DESKTOP-LIJQMSN:/mnt/c/Users/ihen$ ls folder/
a b c d e
yiheng@DESKTOP-LIJQMSN:/mnt/c/Users/ihen$ find folder/ -mindepth 1 -not -path folder/d
folder/a
folder/b
folder/c
folder/e
yiheng@DESKTOP-LIJQMSN:/mnt/c/Users/ihen$ find folder/ -mindepth 1 -not -path folder/d -delete
yiheng@DESKTOP-LIJQMSN:/mnt/c/Users/ihen$ ls folder/
d
yiheng@DESKTOP-LIJQMSN:/mnt/c/Users/ihen$