Function return codes

In a bash function, return will return the status code of the previous command. For many years, I thought it returned the default status, i.e. 0, but it does not.

foo() {
  ls /does/not/exist
  return
}

foo || {
  printf "Function 'foo' failed" 
}

So if you want foo to return 0/success even when the ls /does/not/exist fails, you must be explicit:

foo() {
  ls /does/not/exist
  return 0
}

Wish I'd learned about this sooner (took me around 22 years of bash coding).


~ /home 🏠 ~ talks 💬 ~ bash ~ craftsmanship ~ db ~ dongxi ~ emacs ~ escenic ~ iam ~ java ~ js ~ language ~ latex ~ ldap ~ life ~ linux ~ llm ~ mac-os-x ~ mt-foo ~ network ~ norsk ~ python ~ quotes ~ running ~ security ~ travel ~ unix ~ various ~ vcs ~ webdesign ~ windows ~ discoveries ~ cv 🧙 ~

Licensed under CC BY Creative Commons License ~ 📡 RSS feed ~ ✉ torstein.k.johansen @ gmail ~ 🐘 @skybert@hachyderm.io ~ 🎥 youtube.com/@skybert