我需要制作一个 bash 脚本来检查文件或目录是否存在,如果文件存在,它会检查可执行权限。我需要修改脚本以便能够通过参数赋予文件可执行权限。
示例:控制台输入 ./exist.sh +x file_name
应该使文件可执行。
这是未完成的代码,用于检查文件/目录是否存在以及文件是否可执行。我需要添加 chmod
参数部分。
#!/bin/bash
file=$1
if [ -x $file ]; then
echo "The file '$file' exists and it is exxecutable"
else
echo "The file '$file' is not executable (or does not exist)"
fi
if [ -d $file ]; then
echo "There is a directory named '$file'"
else
echo "There is no directory named '$file'"
fi
最佳答案
如果您的脚本有可选参数,您需要先检查它们。
在只有几个简单参数的情况下,显式检查它们会更简单。
MAKEEXECUTABLE=0
while [ "${1:0:1}" = "+" ]; do
case $1 in
"+x")
MAKEEXECUTABLE=1
shift
;;
*)
echo "Unknown option '$1'"
exit
esac
done
file=$1
然后在你确定文件不可执行之后
if [ $MAKEEXECUTABLE -eq 1 ]; then
chmod +x $file
fi
如果您决定添加更复杂的选项,您可能需要使用类似getops
的东西:example of how to use getopts in bash
关于linux - 带有使文件可执行的参数的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27744162/