Bash – How to copy all users .bash_history files into the home directory

bashcommand linescripting

I am running as root. I want to copy all the users on the system's .bash_history files into my home directory. I can do this to combine all of them into one, but then I can't tell who's commands are who's.

find /home/ -maxdepth 2 -iname ".bash_history" -type f -exec cat {} >> ~/combined.txt \;

I would like to either put the user names between each of the files in the combined.txt file, or I would like to copy the files in this type of structure:

~/user-bash/john.txt
~/user-bash/mary.txt
~/user-bash/bob.txt
~/user-bash/larry.txt
~/user-bash/root.txt

How can I accomplish either one (or both) of these?

Best Answer

In zsh, using zmv:

autoload zmv; alias zcp='zmv -C'  # this can go into your .zshrc
zcp '/home/(*)/.bash_history' '~/user-bash/$1.txt'

In other shells:

for x in /home/*/.bash_history; do
  u=${x%/*}; u=${u##*/}
  cp "$x" ~/user-bash/"$u.txt"
done
Related Question