How to know if the script command has been successfully executed?

Asked

Viewed 5,766 times

1

I need the script to identify whether the tar.gz file was successfully generated in an if. Here’s a non-functional example:

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

Very simple I think but could not do! I await answers...

1 answer

6


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

see this example of the cat command on 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 result of "success" because in my tests, when I tried to compress a non-existent file or even putting wrong arguments to compress, simply the command was not executed, 'breaking' thus the script:

#!/bin/bash

tar -zcf escrever.tar.gz escrever.py

if [ $? -eq 0 ]
then
    echo "sucesso"
fi
  • very good, solved my problem, vlw!

  • +1 Your answer is fine, but if you set an example like tar -zcf teste.tar.gz teste/testeDir if [ $? -eq 0 ] etc, applied to the question command, so that other users learn how it is in practice, it is even more cool

Browser other questions tagged

You are not signed in. Login or sign up in order to post.