Bash: correct error handling

I have a bash script similar to:

{
  # Try block
  command 1
  command 2
  command 3
} || {
  # Catch errors
  while true; do
  {
    # Try block inside
    # Change parameters for command 1, command 2
    command 1
    command 2
    command 3
    break
  } || {
      # Change parameters and try again
      continue
  }
done
}

More or less, this code works fine, but ...

For some reason, partitions trydo not work as expected for me. I thought this was a failure if some of my commands return no code 0, but it is not.

In some cases, my command 2returns the code 1in the first try block, but it does not break and goes to the section catch, it command 3is executed from this block tryand it.

Here is my question:

How to handle errors in bash? Just play with return codes?

UPDATE:

The original code looks very similar to: The basic idea is that all 3 commands must be executed one after another, and all of them are somehow related to folder_name.

folder_name=my_folder
suffix=0
{
  cd /home/test/
  mkdir $folder_name
  ls -la $folder_name
} || {
    while true; do
      suffix=$(expr $suffix + 1)
      {
        folder_name=$folder_name_$suffix
        cd /home/test/
        mkdir $folder_name
        ls -la $folder_name
        break
      } || {
          continue
      }
    done
}
+3
2

.

( ). docs here

, . [[ $? -eq 0 ]]. &&. .

{
  cd /home/test/ && 
  mkdir $folder_name &&
  ls -la $folder_name;
}

, .

cd /home/test/
prefix=my_folder                                                                                                                                      
suffix=0

folder_name="$prefix"
while true; do
  if [[ -e $folder_name ]]; then
    folder_name="${prefix}_$((++suffix))"
    continue
  fi  
  mkdir "$folder_name"
  if [[ $? -ne 0 ]]; then
    echo "mkdir failed"
    exit 1
  fi  
  break
done
+1

, , , set -e (== set -o errexit), , script .

, exec'd , exec-ed, -exec'd , , exec'd .

, :

#!/bin/sh -e

echo "EXEC'D SHELL CHILD"
if sh -e <<'EOF'
true(){ echo true; return 0; }
false(){ echo false; return 1; }
true
false 
true
true
EOF
then
    echo SUCCESS
else
    echo FAILED: $?
fi

echo ===========
echo "NON-EXEC'D SUBSHELL"
if (
true(){ echo true; return 0; }
false(){ echo false; return 1; }
true
false 
true
true
)
then
    echo SUCCESS
else
    echo FAILED: $?
fi

:

EXEC'D SHELL CHILD
true
false
FAILED: 1
===========
NON-EXEC'D SUBSHELL
true
false
true
true
SUCCESS

( /bin/ bash /bin/sh - )

, set -e, , && || return 1 ( ), exec'd, :

 sh -ec' command 1
  command 2
  command 3' || ...

 {  comman 1 && command 2 && command 3; } || ... 
+1

Source: https://habr.com/ru/post/1683379/


All Articles