Results 1 to 4 of 4

Thread: Chaining commands in bash script using &&

  1. #1
    Join Date
    Apr 2009
    Beans
    300
    Distro
    Xubuntu 22.04 Jammy Jellyfish

    Chaining commands in bash script using &&

    I need to write a bash script in which every command is conditional upon the successful execution of the previous command and if any command fails no following commands will be executed. I would rather not have each statement embedded in an "if" statement. So far this is what I'm thinking about doing:
    Code:
    #!/bin/bash
    
    comand1
    [ $? ] && command2
    [ $? ] && command3
    [ $? ] && command4
    [ $? ] && command5
    Is this OK? Is there a better way?

  2. #2
    Join Date
    Sep 2006
    Beans
    8,627
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: Chaining commands in bash script using &&

    You can connect them directly:

    Code:
    #!/bin/bash
    
    comand1 && command2 && command3 && command4 && command5
    If that is hard to read in your script, then you can split the line using a backslash at the end of the line.

    Code:
    #!/bin/bash
    
    comand1 \
    && command2 \
    && command3 \
    && command4 \
    && command5

  3. #3
    Join Date
    Feb 2007
    Location
    Romania
    Beans
    Hidden!

    Re: Chaining commands in bash script using &&

    You can use `set -e', check out BashFAQ 105 (link in my signature).

    But, I would do something like:
    Code:
    command1 || exit 1
    command4 || { echo "command4 failed" >&2; exit 4; }
    If you want to use verbose error messages you could write a little function to keep your code clean and organized:

    Code:
    #!/bin/bash
    
    err()
    {
        r="$1"
         case "$r" in
            1)  printf '%s\n' "error 1" >&2 ;;
            2)  printf '%s\n' "error 2" >&2 ;;
            4)  printf '%s\n' "error 4" >&2 ;;
            *)  printf '%s\n' "unknown error" >&2 ; exit -1 ;;
        esac
    exit "$r"
    }
    
    command1 || err 1
    command2 || err 2
    command3 || err 4
    
    exit 0
    Last edited by sisco311; July 22nd, 2014 at 07:57 AM.

  4. #4
    Join Date
    Apr 2009
    Beans
    300
    Distro
    Xubuntu 22.04 Jammy Jellyfish

    Re: Chaining commands in bash script using &&

    Thanks for all the suggestions. I think I'll go with 'set -e' as that solution seems the simplest for the commands I'll be using.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •