When I use piped xargs with subshell for echo I get this
user@DESKTOP-P560BV8:~/tmp/t$ echo ./foo/bar.jpg | xargs -I{} echo "$(basename {})"
./foo/bar.jpg
However, this works
user@DESKTOP-P560BV8:~/tmp/t$ echo ./foo/bar.jpg | xargs -I{} basename {}
bar.jpg
and if I inline the parameter value
user@DESKTOP-P560BV8:~/tmp/t$ echo "$(basename ./foo/bar.jpg)"
bar.jpg
I don't understand why is it behaves like that? I need xargs to execute on each line of the text separately, so -0 parameter is not an option
CodePudding user response:
If you want to execute basename in a subshell then use it this way:
echo './foo/bar.jpg' |
xargs -I {} bash -c 'echo "$(basename "$1")"' _ '{}'
bar.jpg
We are passing dummy value _ as $0 for subshell and placeholder {} will be passed to subshell as $1
