错误检查 - shellscript

时间:2017-07-02 16:14:02

标签: bash

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

代码:

#!/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 个答案:

答案 0 :(得分: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