尝试创建一个bash脚本,将文件移动到回收站目录中,并具有其他一些功能。为了实现这些功能,我正在尝试使用getopts函数,但我正在努力实现帮助功能或用户手册。当我运行脚本并尝试使用-h时,脚本没有识别出它是一个选项,只是正常运行,就像它是一个文件一样。我该如何解决这个问题呢?已修复:
#!/bin/bash
trash=~/TRASH
if [ ! -e $trash ]; then
mkdir $trash
elif [ ! -d $trash ]; then
echo "$0: error: $trash is not a directory"; exit 1
fi
while getopts "h" options; do
case $options in
h) echo "This is the help option."
exit;;
\?)
echo: "Invalid option"
exit;;
esac
done
while [ $# -gt 0 ]; do
if [ ! -e $1 ]; then
echo "$0: error: tried to delete file that does not exist: $1"
shift
continue
fi
tarname="$1.tar"
tar -cf "$tarname" "$1"
mv "$tarname" $trash
rm -rf "$1"
shift
done
echo "Cleaning $trash directory"
now=`date +%s`
cd $trash
for f in `ls`; do
fileage=$(stat -c '%Y' "$f")
if [ $((now-fileage)) -gt $((60*60*24*2)) ]; then
rm -rf "$f"
fi
done发布于 2021-07-07 22:27:29
这是一个简单的修复,只需将getopts函数移动到顶部,在任何其他操作之前发生,现在它就可以工作了。
https://stackoverflow.com/questions/68287733
复制相似问题