Bash Script Error Catching

前端 未结 3 1701
庸人自扰
庸人自扰 2021-02-05 16:28

I am very new to bash scripts, and for my first script attempt I am submitting files to my professor\'s dropbox within the same server.

The code is this:



        
相关标签:
3条回答
  • 2021-02-05 16:57

    Although you can test $?, you can also test the exit status of a command directly:

    if cp -rv /path/to/lab$1 /path/to/dropbox
    then echo Submission successful
    fi
    exit $?
    

    The errors were already reported to standard error by cp. The exit shown will exit with status 0 (success) if cp was successful; otherwise, it exits with the status that cp exited with.

    Clearly, you can wrap that in a loop if you want to, or you can make it non-interactive (but any exit terminates the script).

    0 讨论(0)
  • 2021-02-05 16:58

    To check the return code from the previous command, you can use the $? special variable as follows:

    if [ "$?" -ne "0" ]; then
      echo "Submission failed"
      exit 1
    fi
    
    echo "Submission successful."
    

    Additionally, if you want a clean prompt, you can redired stderr as explained here.

    Finally, you can also use this in the script that uses scp, since it works regardless of the command you're using.

    0 讨论(0)
  • 2021-02-05 17:02
    echo "Submit lab$1?"
    
    read choice
    
    echo "Send to Prof's dropbox"
    cp -rv /path/to/lab$1 /path/to/dropbox &>/dev/null
    
    [ $? -eq 0 ] && { #success, do something } || { #fail, do something }
    

    And so on...

    0 讨论(0)
提交回复
热议问题