How do I know if script command was executed successfully?

1

I need the script to identify if the tar.gz file was successfully generated in an if. Here is a nonfunctional example:

VAR=tar -zcf teste.tar.gz teste/testeDir
if [VAR]
then
echo "Sucesso"
else
echo "Erro"
fi

Pretty simple I think but I could not do it! I await answers ...

    
asked by anonymous 29.07.2016 / 20:14

1 answer

5

use the variable $? it returns "0" if the last command was successfully executed, and returns "1" if there was an error in this command.

Below is a table with these special variables that are available in the shell:

Variable Description

  • $ 0 Parameter number 0 (name of the command or function)
  • $ 1 Parameter number 1 (from the command line or function)
  • ... Parameter number N of the command line or function)
  • $ 9 Parameter number 9 (from the command line or function)
  • $ {10} Parameter number 10 (from the command line or function)
  • $ # Total number of command line parameters or function
  • $ * All parameters, as a single string
  • $ @ All parameters, such as multiple protected strings
  • $$ PID of the current process (from the script itself)
  • $! PID of the last background process
  • $ _ Last argument of the last command executed
  • $? Return value of last executed command

See this example of the cat command in my terminal:

felix@asgard:[~]: cat escrever.py 
arq = open('arquivo.txt','w')
arq.write("Pyhton é legal")
arq.close()
felix@asgard:[~]: echo $?
0
felix@asgard:[~]: cat escreve.py 
cat: escreve.py: No such file or directory
felix@asgard:[~]: echo $?
1

In the example below I only put the "success" result because in my tests, when I tried to compress a non-existent file or even putting wrong arguments to compress, simply the command would not execute, thus 'breaking' the script:

#!/bin/bash

tar -zcf escrever.tar.gz escrever.py

if [ $? -eq 0 ]
then
    echo "sucesso"
fi
    
29.07.2016 / 20:23