bash - Script that uses variable username in find command -


i'm trying write script lists absolute paths of of given user's home files , directories, recursively, , writes of them array. currently, i'm using find ...

user="foobar" usershomefiles=( $(find ~$user -printf "%p\\n") ) 

however, when execute script tells me ...

find: `~foobar': no such file or directory 

even though foobar valid user home directory. same error running user="root". ideas how fix find command works in script?

this happens because in bash "tilde expansion" happens before "parameter expansion". tilde expansion attempts find user "$user", fails , tilde remains unchanged. next comes "parameter expansion" substituting "$user" "foobar". see bash(1) "expansion" section.

one way "eval", this:

user_home=`eval "echo ~$user"` 

another directly querying passwd database, this:

user_home=`getent passwd "$user" | cut -d: -f6` 

however, note array assignment break if user home directory contains filenames spaces or tabs.

you can read them more reliably "readarray", this:

readarray -t usershomefiles < <(find "$user_home") 

Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -