For a bash
-only solution with no potentially expensive calls to external programs (only important if you do it a lot, which may not be the case here):
pax> export x=a ; if [[ "${x%%_*}" != "${x}" ]]; then
...> export bkpdir=/backups/${x%%_*}/backup
...> else
...> export bkpdir=/backups/others/backup
...> fi
pax> echo " ${bkpdir}"
/backups/others/backup
pax> export x=a_b ; if [[ "${x%%_*}" != "${x}" ]]; then
...> export bkpdir=/backups/${x%%_*}/backup
...> else
...> export bkpdir=/backups/others/backup
...> fi
pax> echo " ${bkpdir}"
/backups/a/backup
The if
statement detects if there's an underscore by checking a modified string against the original. If there is an underscore, they will be different.
The ${x%%_*}
gives you the string up to the removal of the longest _*
pattern (in other words, it deletes everything from the first underscore to the end).
A (slightly) simpler variant would be:
export bkpdir=/backups/others/backup
if [[ "${x%%_*}" != "${x}" ]]; then
export bkpdir=/backups/${x%%_*}/backup
fi