1

Often, I find my self writing the following in BASH script,

if [ -f /very/long/path/tofile/name ]; then
   do_someting /very/long/path/tofile/name
fi

For example:

if [ -f /usr/local/bin/virtualenvwrapper.sh ]; then
   source /usr/local/bin/virtualenvwrapper.sh
fi

The obvious way to short-cut it would be:

WRAPPER=/usr/local/bin/virtualenvwrapper.sh
if [ -f ${WRAPPER} ]; then
   source ${WRAPPER}
fi

But I am wondering if there is some kind of a built-in variable to spare me the manual declaration?

oz123
  • 27,559
  • 27
  • 125
  • 187

1 Answers1

5

You can with && operator:

test -f file &&  cat file

The command after && will run only if first command run successfully.

See: Run command2 only if command1 succeeded in cmd windows shell

If you want to write /very/long/path/tofile/name only once you can define a function and just run it.

function run_smart {
  if [ -f "$2" ]; then
     "$1" "$2"
  fi
}

run_smart cat /very/long/path/tofile/name
Community
  • 1
  • 1
Florin Ghita
  • 17,525
  • 6
  • 57
  • 76