2017-07-02 45 views
1

我是新来的shell脚本,我正在写这个脚本来创建具有权限的文件并检查文件是否存在。一切工作正常,但是当我没有指定参数说它缺少参数,但仍然给我没有这样的文件或目录错误,我没有得到。有人可以帮忙吗?错误检查 - shellscript

代码:

#!/bin/bash`enter code here` 
# checking the argument 
if [[ ! $1 ]]; then 
    echo "missing argument, please check !" 
fi 

# variable holding the script name. 
scriptname="$1" 

# creates shellscript and changes the permissions of script to u+x. 
# Adds #!/bin/bash line to script. 
if [[ ! -e "${scriptname}" ]]; then 
    echo "#!/bin/bash" >> "${scriptname}" && chmod u+x "${scriptname}" 
else 
    echo "file " ${scriptname} " exists, create a new file." 
fi 
+1

'回声后“失踪的说法,请检查!”'你可能要添加'exit 1'声明(下一行) – janos

+1

@janos感谢您的纠正,现在工作正常。 – Arun

回答

0

这里的根本问题是,经过条件满足由 @janos[ here ]指针你不退出程序。因此,解决问题的方法是

if [[ ! $1 ]]; then 
    echo "missing argument, please check !" 
    exit 1 # A non zero exit status implies an error in Linux 
fi 

然而,一个更合适的方法做同样是使用[ param expansion ]

if [ ${1:-no_file_entered} = "no_file_entered" ]]; then 
    echo "missing argument, please check !" 
    exit 1 # A non zero exit status implies an error in Linux 
fi