-1

I'm looking for a way to shorten this piece of code to remove the echo $? part.

case 0 in  
    $( [[ -e /path/to/file/a ]]; echo $?) ) echo a ;;   
    $( [[ -e /path/to/file/b ]]; echo $?) ) echo b ;;  
esac  

It feels like bash should have a way to expand to a commands exit value without having to have an extra echo statement included.

I've spent a good 30 minutes Googling command expansion, but I didn't find anything that would eliminate the echo from the above example.

Possibly it's just wishful thinking, but in any case I'd love to have a definite answer and or hear any comments.

Phillmac
  • 109
  • 7

1 Answers1

3

Perhaps I'm missing something, but wouldn't something like

if [ -e /path/to/file/a ]; then
  echo a
elif [ -e /path/to/file/b]; then
  echo b
fi

or

for f in a b; do
  if [ -e /path/to/file/"$f" ]; then
    echo $f
    break
  fi
done

be a more straightforward approach?

If you need to handle a growing list of locations I'd specifically prefer the second approach, as it allows you to define the list at the beginning of the script rather than somewhere deeper in your code:

locations=( '/path/to/file/a' '/path/to/file/b' )

or

declare -a locations=()
locations+=('/path/to/file/a')
locations+=('/path/to/file/b')

You can handle different locations in different ways by nesting a case statement inside the if statement, so that it only applies if the location does exist:

for f in "${locations[@]}"; do
  if [ -e "$f" ]; then
    case "$f" in
      '/path/to/file/b')
        su -c "..." - someuser
        ;;
      *)
        echo "$f"
        ;;
    esac
    break
  fi
done
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
  • I currently have a script that's based around if elif statements that is rapidly growing as I had many many possible file locations, – Phillmac Oct 14 '16 at 02:54
  • So I wanted to see if it was possible to simplify the structure with case statements Also, the echo a or echo b is not always the same command, sometimes there's an su command to execute as a different user depending on which file exists – Phillmac Oct 14 '16 at 02:58