Backport #38885 by @wxiaoguang make the "command variable replacement" more accurate and OS-independent, add a test for it. Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>