Linux 接受参数和条件Bash
我正在尝试制作一个脚本,它只包含一个命令行参数。然后它查看参数,如果它是一个目录名,它只打印这个目录存在。如果是文件名,则会打印出文件存在。否则,它将尝试创建具有此名称的目录,并测试其是否成功,并在标准输出中报告此情况 我的代码是:Linux 接受参数和条件Bash,linux,bash,shell,Linux,Bash,Shell,我正在尝试制作一个脚本,它只包含一个命令行参数。然后它查看参数,如果它是一个目录名,它只打印这个目录存在。如果是文件名,则会打印出文件存在。否则,它将尝试创建具有此名称的目录,并测试其是否成功,并在标准输出中报告此情况 我的代码是: while read argument; do if [ $argument -d ]; then echo "Directory exists" elif [ $argument -e ] echo "File
while read argument; do
if [ $argument -d ]; then
echo "Directory exists"
elif [ $argument -e ]
echo "File exists"
else
mkdir $argument
if [ $argument -d]; then
echo "Directory was created"
else
echo "Error while creating the directory"
fi
fi
done
然后运行代码
/file\u name.sh参数
。如果我像这样运行代码,我会在第8行得到一个错误,那就是“else”。虽然这里可能没有必要,但我想到的第一个选项是如何从命令行接受参数。如您所述,您需要单个命令行参数,因此无需循环
#!/bin/bash
if [[ -z "$1" ]]; then
echo "Help : You have to pass one argument"
exit 0
fi
if [[ -d "$1" ]]; then
echo "Directory exists"
elif [[ -f "$1" ]]; then
echo "File exists"
else
mkdir "$1"
if [ -d "$1" ]; then
echo "Directory was created"
else
echo "Error while creating the directory"
fi
fi
多亏了提供的链接,我制定了这个解决方案,谢谢。复制粘贴您的脚本并修复显示的错误-
如果[$argument-d]
您认为这有什么用?!在elif
read
从STDIN而不是命令行参数中读取后,您缺少了一个然后
。请引用您的变量!如前所述;他是你的朋友。
if [ -d $1 ]; then
echo "Directory exists"
elif [ -e $1 ]; then
echo "File exists"
else
mkdir $1
if [ -d $1 ]; then
echo "Directory was created"
else
echo "Error while creating the directory"
fi
fi