This looks quite verbose to me, using the command substitution and echo:

# Source file
source=$( [[ ! -z "$1" ]] && echo "/home/$1" || echo '/root' )
[[ ! -f "$source" ]] && echo "History file '$source' not found." 1>&2 && exit 1;

# Am I dealing with root
isRoot=$([[ "$source" =~ ^/root ]] && echo 1 || echo 0 )

Is there a cleaner (maybe faster?) manner to assign a value to variable depending on some condition?


1 Answer 1


A clearer way would be to establish a default for the user, then locate the Bash history file for that user.

You're making the assumption that the user's home directory will be in /home, and that a root user's home directory will be /root. That's a convention for Linux, but it won't be true at larger Linux installations, and it isn't the convention for other operating systems. Here's one way to do the lookup for systems that use GNU libc:

histfile="$(getent passwd "$user" | cut -d: -f6)/.bash_history"

A cross-platform way is to use tilde expansion, though the eval could be dangerous if the input is untrustworthy:

histfile=$(eval echo "~${1-root}")/.bash_history

The isRoot check should be done on the username (or UID) instead of the home directory. It feels very unconventional to assign a boolean variable in Bash. Keep in mind that the convention is that zero statuses are considered "true" and non-zero statuses are considered "false". I'd advise you not to write that statement at all, but can't really advise you what to do instead since you haven't shown us what you intend to do with that variable.

  • \$\begingroup\$ Thank you for your time spent here. The whole script is meant to backup the argument's (user) bash history file. If backup file exists, then a temporary file is filled with the backup's content + the original bash_history file. Afterwards, the resulting file is filtered with some grep and sed commands to strip off non interesting command lines. Finally, this second output is dumped into the bash_history backup file. isRoot flag is just meant to fallback to the root user in case no argument is supplied. \$\endgroup\$
    – Stphane
    Commented Feb 18, 2016 at 23:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.