Piz*_*man 7 directory shell mkdir
我想输入目录的名称并检查它是否存在.如果它不存在我想创建但我得到错误mkdir: cannot create directory'./' File exists
我的代码说文件存在,即使它不存在.我究竟做错了什么?
echo "Enter directory name"
read dirname
if [[ ! -d "$dirname" ]]
then
if [ -L $dirname]
then
echo "File doesn't exist. Creating now"
mkdir ./$dirname
echo "File created"
else
echo "File exists"
fi
fi
Run Code Online (Sandbox Code Playgroud)
Gil*_*il' 15
Run Code Online (Sandbox Code Playgroud)if [ -L $dirname]
查看此行生成的错误消息:"[:missing`]'"或其他一些(取决于您正在使用的shell).你需要在括号内有一个空格.除非使用双括号,否则还需要围绕变量扩展使用双引号; 你可以学习规则,也可以使用一个简单的规则:总是在变量替换和命令替换周围使用双引号 - "$foo", "$(foo)".
if [ -L "$dirname" ]
Run Code Online (Sandbox Code Playgroud)
然后出现了一个逻辑错误:只有在存在未指向目录的符号链接时才会创建目录.你可能意味着在那里有一个否定.
不要忘记在脚本运行时可能会创建目录,因此您的检查可能会显示该目录不存在,但在您尝试创建目录时该目录将存在.永远不要"检查然后做",总是"做并抓住失败".
如果目录不存在,创建目录的正确方法是
mkdir -p -- "$dirname"
Run Code Online (Sandbox Code Playgroud)
(双引号在大小写中$dirname包含空格或通配符,--以防万一-.)
试试这个代码:
echo "Enter directory name"
read dirname
if [ ! -d "$dirname" ]
then
echo "File doesn't exist. Creating now"
mkdir ./$dirname
echo "File created"
else
echo "File exists"
fi
Run Code Online (Sandbox Code Playgroud)
输出日志:
Chitta:~/cpp/shell$ ls
dir.sh
Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New1
File doesn't exist. Creating now
File created
chitta:~/cpp/shell$ ls
New1 dir.sh
Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New1
File exists
Chitta:~/cpp/shell$ sh dir.sh
Enter directory name
New2
File doesn't exist. Creating now
File created
Chitta:~/cpp/shell$ ls
New1 New2 dir.sh
Run Code Online (Sandbox Code Playgroud)
小智 5
read -p "Enter Directory Name: " dirname
if [[ ! -d "$dirname" ]]
then
if [[ ! -L $dirname ]]
then
echo "Directory doesn't exist. Creating now"
mkdir $dirname
echo "Directory created"
else
echo "Directory exists"
fi
fi
Run Code Online (Sandbox Code Playgroud)
试试这个:ls yourdir 2>/dev/null||mkdir yourdir,它小巧简洁,可以完成你的任务。