我正在尝试处理输入是否仅包含文件名或文件目录
D:\SYSTEM\System\Quality controlled songs\My drip Confession.flac
和 My drip Confession.flac
这是我构建的
#checks if the input is a directory
if [[ -d $filename ]]; then
echo "Extracting Filename and Directory: $filename "
#this extracts the directory of the input
directory=$(dirname "$filename")
#this extracts the filename of the input
filename=$(basename "$filename")
#this makes the rest of the code execute in the input directory
cd "$directory"
#checks if the input is a file
elif [[ -f $filename ]]; then
echo "Extracting Filename: $filename "
else
echo "Invalid input: $filename "
exit 1
fi
当我输入
D:\SYSTEM\System\Quality controlled songs\My drip Confession.flac
时,它会输出 Extracting Filename: $filename
当它不应该这样做时,因为它包含路径
那我该怎么办?
我刚刚使用了参数 -d 和 -f。
如果您想知道用户是否输入了文件名或路径名,应使用选项 -f 调用脚本。 解决方案是验证用户是否输入了第一个选项 -f 或者不使用 if[ "$1"="-f"]; 。 这是我向您提出的一个简单的解决方案:
#!/bin/bash
if [ "$1" = "-f" ]; then
if [ -n "$2" ]; then
finalname=$(basename "$2")
echo "File name is: $finalname "
filepath=$(dirname "$2")
echo "File path is: $filepath "
else
echo "Please enter a file name after option -f."
fi
else
echo "Please use -f"
fi
我希望这能回答你的问题,如果有人能纠正我的推理或在这次讨论中添加更多内容,我将很高兴。 快乐编码!